phpmysqlescapingwildcardsql-like

php building a mySQL query with a wildcard


Cant seem to figure out whats wrong, the query should be correct, and it works in phpMyAdmin but when I introduce a wildcard into the php string "%", every query fails.

This works:

$query = sprintf("SELECT `id`FROM `table`WHERE `name` LIKE '".$resources[1]."'", 
                                                                   mysql_real_escape_string($resources[1]));

This does not:

$query = sprintf("SELECT `id`FROM `table`WHERE `name` LIKE '%".$resources[1]."%'", 
                                                                   mysql_real_escape_string($resources[1]));

The query Im obviously trying to generate is

SELECT `id` FROM `table`WHERE `name` LIKE '%someName%'

Solution

  • Read the sprintf man page: http://php.net/sprintf

    $sql = sprintf('..... '%%%s%%', $var);
                           ^^--- turns into %
                             ^--  %s -> $var
                               ^^-- turns into %
    

    Your code, as written, does NOTHING to prevent sql injection, since you're not using sprintf() properly.