简体   繁体   中英

php variable in sql query

I have this:

$result = mysql_query("SELECT * FROM animals WHERE hand= " .$_SESSION['SESS_HAND']. ");

But always shows "Parse error: parse error, expecting T_STRING' or T_VARIABLE' or `T_NUM_STRING"

Always escape string variables :

$result = mysql_query("SELECT * FROM animals WHERE hand= '" .
mysql_real_escape_string($_SESSION['SESS_HAND']). "'");

The reason your query does'nt work is because the value of your WHERE is'nt between single quotes.

EDIT: Quentin is right too, you did'nt close the quotes at the last bracket ;).

This would make the query work:

$result = mysql_query("SELECT * FROM animals WHERE hand= '" .$_SESSION['SESS_HAND']. "'");

But like a1ex07 points out, you should allways escape variables! Above query is vulnerable to MySQL injections. Underneath example shows the correct way by escaping the variable, and in my opinion is a bit better readable code ;).

$query = "SELECT * FROM `animals` 
WHERE `hand` = '" .mysql_real_escape_string($_SESSION['SESS_HAND']). "'";

mysql_query($query);

try:

$result = "SELECT * FROM animals WHERE hand= " . $_SESSION['SESS_HAND'];

mysql_query($result);

Also, by doing this, you can debug your query and see exactly what it's doing in SQL by writing:

echo $result;

It gives that error message because you never finish the string that you try to append after the session data: "); .

Don't build SQL queries by mashing together strings though. Use prepared statements and parameterized queries .

Problem:

$result = mysql_query("SELECT * FROM animals WHERE hand= " .$_SESSION['SESS_HAND']. ");

Solution:

if (!$sessHand = mysql_real_escape_string($_SESSION['SESS_HAND']))
{ 
echo "There was a error: " . mysql_error();
}
else
{ $result = mysql_query("SELECT * FROM animals WHERE hand=$sessHand") }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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