Frage

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.

War es hilfreich?

Lösung

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.

Andere Tipps

The trailing % that you have in your LIKE clause is present in your exact search. The % only has meaning when using LIKE, so it is looking for an exact match of whatever you're passing, but with a % on the end.

LIKE 'criteria%' will find anything that BEGINS with criteria

= 'criteria%' will match that literal exactly, including the %.

You can use % with LIKE Clause, just change your code like below...

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

Try to properly end query string with double quotes:

$sch = "SELECT record_key, surname, given_names, birth_date, death_date, age
 FROM records
 WHERE surname LIKE '".addslashes($name)."%'";
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top