开发者

Escaping string for MySQL statement

开发者 https://www.devze.com 2023-01-24 07:56 出处:网络
I have the following select statement: $res = mysql_query(\"select * from Table where Name=\'{$_REQUEST[\'name\']}\'\");

I have the following select statement:

$res = mysql_query("select * from Table where Name='{$_REQUEST['name']}'");

However, since this kind of query is prone to SQL injection, I am using a more secured way for the selection:

$escaped_name=mysql_real_escape_string($_REQUEST['name']);
$res = mysql_query("select * from Table where Name='{$escaped_name}'");

It all works fine until I try to run the selection with a $_REQUEST['name'] that contains the string Joel's .In that case the selection doesn't work. After debugging and printing the conte开发者_Python百科nt of $escaped_name to the screen, I got the following:

Joel\\\'s

What is the reason for this? It seems like the string was escaped automatically, and then I escaped it again.


The data was probably auto-escaped by PHP's (deprecated) "magic quotes" feature. To disable magic quotes in .htaccess:

php_flag magic_quotes_gpc off
php_flag magic_quotes_runtime off


You've run into an issue in PHP caused by a "feature" called Magic Quotes. PHP attempts to escape strings when Magic Quotes is enabled, but as different databases have different escaping schemes, the results can be pretty useless, or even dangerous.

There are two possible solutions. the simplest, and recommended solution is to just turn magic quotes off in php.ini or .htaccess.

The second approach is to use magic_quotes_gpc to test if the feature is enabled, then running stripslashes on your input if it is. Then run mysql_real_escape_string on the result.


Not sure what you mean by "run the selection" but i would guess from what you're saying that you have magic quotes turned on.

If you dont have access to the php.ini either check phpinfo() or add this to a file:

if(get_magic_quotes_gpc()){
  echo "on";
}else{
  echo "off";
}

If they are turned on they can be disabled in various places such as php.ini or .htaccess files


The safest way is by using prepared statements which avoids escaping. The automatic escaping is caused by magic quotes and can be disabled using these methods.

An instant solution (assuming you leave magic quotes enabled) would be:

mysql_real_escape_string(stripslashes($_REQUEST['name']));

0

精彩评论

暂无评论...
验证码 换一张
取 消