phpsqlwhere-clausesql-likeaddslashes

SQL search changed from like to equals not working


php/sql newbie. Trying to change a LIKE name search into an exact search. Fails to find any records even when use search values that I know are in the table.

Original code:

 $sch = "SELECT record_key, surname, given_names, birth_date, death_date, age
               FROM records
               WHERE surname LIKE '".addslashes($name)."%';
    $result = mysql_query($sch);

New code:

 $sch = "SELECT record_key, surname, given_names, birth_date, death_date, age
               FROM records
               WHERE surname = '".addslashes($name)."%';
    $result = mysql_query($sch);

I have tried everything I can think of, including:

 WHERE surname = 'addslashes($name)';

(I wasn't sure of the reason for the " each end or the %)

The only way I can get it to work is if I scrap the addslashes and just use: WHERE surname = '$name';

which I understand is vulnerable to injection.


Solution

  • Try:

     $sch = "SELECT record_key, surname, given_names, birth_date, death_date, age
                   FROM records
                   WHERE surname = '".addslashes($name)."'";
        $result = mysql_query($sch);
    

    without the %.

    % is a wildcard in LIKE patterns, but is a regular character in = ones.