including variable in a mysql select statement [Solved]

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
rianne809
Forum Newbie
Posts: 1
Joined: Wed Mar 21, 2007 7:08 am

including variable in a mysql select statement [Solved]

Post 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.
Last edited by rianne809 on Tue Apr 24, 2007 4:47 am, edited 2 times in total.
User avatar
CoderGoblin
DevNet Resident
Posts: 1425
Joined: Tue Mar 16, 2004 10:03 am
Location: Aachen, Germany

Post 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
Post Reply