开发者

Adding variables in query the right way

Why do this..

开发者_运维问答
$fruit_type = "banana";
mysql_real_escape_string($fruit_type);

$query = "SELECT * FROM posts WHERE fruit = " . $fruit_type . ";    

when you can do this..

$fruit_type = "banana";
mysql_real_escape_string($fruit_type);

$query = "SELECT * FROM posts WHERE fruit = $fruit_type;

I know that integers should be encapsulated in single quotes but is it fine to add a variable that contains a string directly?


Adding a string directly, without quotes (and escaped quotes within the value) will not work if that is your question.

The following will work with integers, provided you are matching on an number field, but it will not work with strings:

$query = "SELECT * FROM posts WHERE fruit = $fruit_type";

To match strings, you must enclose them within single quotes, and escape single quotes occurring within the value. The following will not escape quotes contained within the passed variable:

$query = "SELECT * FROM posts WHERE fruit = '$fruit_type'";

At the very least, you should do this:

$query = "SELECT * FROM posts WHERE fruit = " . mysql_real_escape_string($fruit_type); 

And at the first opportunity, read about these:

http://php.net/manual/en/pdo.prepared-statements.php


Typically, no. The reason is just this:

$fruit_type = "; DELETE FROM posts;";

There's nothing inherently wrong with the syntax, it's your approach in general. You want to make sure that all user input strings are escaped.


I think you missed the quotes for the string.

$query = "SELECT * FROM posts WHERE fruit = '$fruit_type';

Also, its a good practice to use bind variables in SQL in order to avoid DB query parsing


To late but it will help others `

$table ="table_Name";
$idx="value";
$sql="SELECT * FROM $table WHERE row_name= '$idx'";

` execute your query .

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜