php variable in sql query

33,559

Solution 1

Always escape string variables :

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

Solution 2

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);
Share:
33,559
Jonh Camel
Author by

Jonh Camel

Updated on July 07, 2022

Comments

  • Jonh Camel
    Jonh Camel almost 2 years

    I have this:

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

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

    • Willy
      Willy over 11 years
      Do you realise that you have a " right before your ); at the end of the string? Making it escape it.
  • Admin
    Admin over 11 years
    What kind of status message is that?
  • Willy
    Willy over 11 years
    Welcome to SO slipfeed! Please try to use a "mature language" here!