Adding variables to the query in 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 it.

 $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 nice to add a variable containing a string directly?

+4
source share
4 answers

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 if you match in a numbers field, but it will not work with strings:

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

To match strings, you must enclose them in single quotes and avoid single quotes occurring inside the value. Below, the quotes contained in the passed variable will not be executed:

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

At least you should do this:

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

And as soon as possible read about it:

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

+1
source

Generally not. The reason is that:

 $fruit_type = "; DELETE FROM posts;"; 

There is nothing wrong with the syntax; this is your whole approach. You want all user input lines to be escaped.

+1
source

I think you missed the quotes for the string.

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

Also, his good practice is to use bind variables in SQL in order to avoid parsing the SQL query

0
source

Late, but it will help others`

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

`fulfill your request.

-2
source

All Articles