mysql select record with an escaped quote

独自空忆成欢 提交于 2019-12-11 18:52:52

问题


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!


回答1:


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.



来源:https://stackoverflow.com/questions/23588294/mysql-select-record-with-an-escaped-quote

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!