PHP SQL语句转义
我想使用以下语句向每个用户显示他们调用的位置:
$result = mysql_query("SELECT `CallerNumber`, `CalleeNumber`, `ServiceCost` FROM `calls` WHERE `Customer_ID` = $current_user['CustomerID']");
$current_user['CustomerID']
部分导致了错误。我尝试将其放在带有 / 转义符的单引号内,但它不起作用。这怎么能做到呢?
I wanted to show each user where they called using this statement:
$result = mysql_query("SELECT `CallerNumber`, `CalleeNumber`, `ServiceCost` FROM `calls` WHERE `Customer_ID` = $current_user['CustomerID']");
The $current_user['CustomerID']
part is causing the error. I tried to put it inside single quotes with / escapes, but it didn't work. How can this be done?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我已经有一段时间没有接触 PHP 了,但我想你需要的是这样的:(
我刚刚查了一下
mysql_real_escape_string
,如果不是常用的,抱歉。)另外,转义是用反斜杠完成的(\),而不是正斜杠 (/)
It's been a while since I did PHP, but I think what you need is this:
(I just looked up
mysql_real_escape_string
, apologies if it's not the commonly used one.)Also, escaping is done with a backslash (\), not a forward slash (/)
你可以试试下面这个。
You could try this below.
唯一正确的答案是:
如果参数不是由程序本身生成的话,首先对参数进行转义。
永远是个好主意!您要注入查询的转义变量。
使用 PDO 是一个更好的主意,但那是另一个主题了。
然后用单引号将注入的变量括起来 否则转义将不起作用!
如果
$var
包含空格或其他特殊变量,这也可以防止 SQL 语句中出现语法错误。不需要在列名周围使用反引号,除非您在列名中使用保留字 或者在列/表名称中使用空格或其他奇怪的字符
The only proper answer is:
First escape the parameter if it was not generated by the program itself.
It a good idea to always! escape vars you are going in inject into a query.
It's an even better idea to use PDO, but that another subject.
Then surround the injected var with single quotes or the escaping will not work!
This will also prevent a syntax error in your SQL statement if
$var
contains a space or other specials vars.Backticks around columnnames are not needed, unless you are using a reserved word for a column name, or you are using spaces or other strange characters in your column/table names
对于双引号或heredocs (EOT) 中的变量(包括数组,甚至来自对象的属性调用),只需将它们括在花括号中即可。
For variables (including arrays and even attribute calls from objects) in double quotes or heredocs (EOT), just enclose them in curly braces.
您可以使用
{$current_user['CustomerID']}
代替$current_user['CustomerID']
仅在以下情况下使用
$current_user['CustomerID']
不是用户输入,否则您应该使用 mysql_real_escape_string() 来避免 SQL注入You could use
{$current_user['CustomerID']}
instead of$current_user['CustomerID']
Only use this in case
$current_user['CustomerID']
is not a user input, otherwise you should usemysql_real_escape_string()
to avoid SQL Injection