简体   繁体   English

php mysql real_escape_string用于整个查询

[英]php mysql real_escape_string for whole query

Is it possible to escape a whole query instead of each searched field. 是否可以转义整个查询而不是每个搜索字段。 For example I know I can do it like this: 例如,我知道我可以这样做:

$name="O'Connor";
$email="mark.O'Connor@something.com";

$name=mysql_real_escape_string($name);
$email=mysql_real_escape_string($email);

$query =("SELECT * FROM TABLE1 WHERE Name = '$name' OR Email = '$email' ");

// code to run query here 

What I am looking for is a way to build my query string like this : 我正在寻找的是一种构建查询字符串的方法,如下所示:

$query=("SELECT * FROM TABLE1 WHERE Name = '$name' OR Email = '$email' ");
$query=mysql_real_escape_string($query); // Can I escape the whole Query ??

// code to run query here 

My reason for asking this Is I have a complex query which is using at around 15 variables from a form and I want to clean them all at once instead of using loads of mysql_real_escape($vairableName)... 我问这个问题的原因是我有一个复杂的查询,该查询正在使用表单中的大约15个变量,我想一次清除所有变量,而不是使用mysql_real_escape($ vairableName)的负载...

Is this possible and can anyone exlplain how I can acheive this 这可能吗,有人可以解释一下我如何做到这一点

Thanks in advance 提前致谢

You can't do that. 你不能那样做。 Escaping changes characters with special meaning in SQL into escape sequences. 转义将SQL中具有特殊含义的字符转换为转义序列。 You need some characters with special meaning so that the query can work. 需要一些具有特殊含义的字符,以便查询可以正常工作。 If you could just escape the entire query, then all database drivers would just do that automatically. 如果您只是可以跳过整个查询,那么所有数据库驱动程序都将自动执行该操作。

eg 例如

$foo = "John O'Reilly";
$sql = "WHERE name='$foo'";
# There are three ' characters here, but only the middle one should be escaped

That said, you should stop using an obsolete database API and pick a modern replacement that supports prepared statements which will save you from having to call real_escape_string all over the place. 就是说,您应该停止使用过时的数据库API,而选择支持已准备好的语句现代替代方法 ,这将使您不必在real_escape_string调用real_escape_string

As others have pointed out, using prepared statements is the best way to go. 正如其他人指出的那样,使用准备好的语句是最好的方法。 But in case you still want to proceed ahead, you can do something like this: 但是,如果您仍然想继续前进,可以执行以下操作:

foreach($_POST as $key=>$value)
{
   // this will take care of escaping all form elements
   $$key = mysql_real_escape_string($value);
}

So if your form contains 3 elements whose names are abc , def , and ghi , the above code will create variables named as $abc , $def , and $ghi respectively. 因此,如果您的表单包含3个名称分别为abcdefghi元素,则上面的代码将创建分别名为$abc$def$ghi变量。

Then you can use them in query as before: 然后,您可以像以前一样在查询中使用它们:

$query = "SELECT * FROM TABLE1 WHERE Name = '$abc' OR Email = '$def'";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM