Search code examples
phpmysqlquotesmysql-real-escape-string

mysql select record with an escaped quote


I have a function where users can pull a record searching by a text field. The input is put into the following SQL query:

$db->query("Select * from users where name = '".$db->real_escape_string($posted_var)."' limit 1");

$db is a mysqli connection object

Works perfect until I have a ' in the name.. then the user is required to manually escape the quote to get it to match........ Shouldn't the real_escape_string() function do that for me?

I have a test record where name is "test\'string" in the database.

$posted_var = "test'string"; // no match 
$posted_var = "test\'string"; // match

Anyone have any idea why real_escape_string() wouldn't add the backslashes?

The MySQL server and this particular table are both utf8_unicode_ci. I don't know what else could cause this....

Thanks for reading!


Solution

  • If the \ is literally inside the text in the db record, then you need

    $sql = "SELECT .... name='foo\\bar'";
                                 ^^---double escaped
    

    The first \ will be stripped off by the DB's sql parser. Then the remaining foo\bar will be used for the field searches.


    comment followup: You're not understanding the purpose of escaping:

    $name = "Miles O'Brien";
    $sql = "SELECT * FROM yourtable WHERE name='" . $db->real_escape_string($name) . "';";
    

    This will produce:

    SELECT * FROM yourtable WHERE name='Miles O\'Brien';
    

    and that's what literally gets send to the DB engine. When the SQL parser gets hold of it, that first \ escape is removed, and the DB will be looking for Miles O'Brien in the name field - note that the backslash is no longer there.

    Since your DB record literally is contains Miles O\'Brien, WITH the \ embedded in the record, you need to double escape, so the query becomes:

    SELECT * FROM yourtable WHERE name='Miles O\\'Brien';
    

    Same thing happens: The SQL parser removes the first layer of escaping, and the DB will now be searching for Miles O\'Brien.