Page 1 of 1

including variable in a mysql select statement [Solved]

Posted: Mon Apr 23, 2007 11:17 pm
by rianne809
Hi guys, im working a php script with mysql, im trying to use a select statement using a variable, here's the example,

$var="test";

$result=mysql_query("SELECT * FROM table WHERE $var='1'");

;im always getting an error on this part with the variable, but if replace the variable with its corresponding value, the script works. Hope you can help me on this. Thanks in advance.

Posted: Tue Apr 24, 2007 3:42 am
by CoderGoblin
I assume that the code shown is not the actual code. When trying to debug things like this I find the following method useful...

Code: Select all

$var="test";
$sql="SELECT * FROM table WHERE {$var}='1'";
echo $sql;
$result=mysql_query($sql);
I normally put squiggly brackets around any variable in a string. They are required if using an array and in my opinion makes the thing more readable. Your method should work (although why a space after the 1 ?)

Regards
Coder