开发者

PHP SQL statement escaping

I wanted to show each user where they called using this sta开发者_Go百科tement:

$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?


It's been a while since I did PHP, but I think what you need is this:

$result = mysql_query("SELECT `CallerNumber`, `CalleeNumber`, `ServiceCost` FROM `calls` WHERE `Customer_ID` = '" . mysql_real_escape_string($current_user['CustomerID']) . "'");

(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.

$arg = $current_user['CustomerID'];
$result = mysql_query("SELECT `CallerNumber`, `CalleeNumber`, `ServiceCost` FROM `calls` WHERE `Customer_ID` = '$arg'");


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.

$arg = mysql_real_escape_string($current_user['CustomerID']);

Then surround the injected var with single quotes or the escaping will not work!

$query = "SELECT CallerNumber, CalleeNumber, ServiceCost 
          FROM calls WHERE Customer_ID = '$arg' ");

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


For variables (including arrays and even attribute calls from objects) in double quotes or heredocs (EOT), just enclose them in curly braces.

$result = mysql_query("SELECT `CallerNumber`, `CalleeNumber`, `ServiceCost` FROM `calls` WHERE `Customer_ID` = {$current_user['CustomerID']}");


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 use mysql_real_escape_string() to avoid SQL Injection

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜