Page 1 of 1

Variable in SQL query

Posted: Mon Jan 11, 2010 3:33 pm
by easinewe
Hello,
I'm building my first PHP site and have run into the following problem. I would like to place a variable within an SQL Request statement but am not certain that I am doing it correctly. The following is the code I was attempting to use.

<?
$sql = "SELECT * FROM `Catalog` WHERE title = '$article['alsolike']'";
$result = mysql_query($sql);
while ( $article = mysql_fetch_array($result) ){
echo '<li class="box"';
echo '>';
echo "<a href=\"detail_pop-up.php?id=" . $article['id']. "\">";
echo '<img src="images/medium/';
echo $article['image'];
echo '.jpg" align="middle" /><br/>';
echo $article['title'];
echo "</li>"; }
?>

In this instance $article['alsolike'] is "Boston". So if it came out as...
$sql = "SELECT * FROM `Catalog` WHERE title = 'Boston'";
the information following it would echo correctly.

Any advice on how to do this correctly would be appreciated.

Thanks!

Re: Variable in SQL query

Posted: Mon Jan 11, 2010 3:39 pm
by AbraCadaver
What do you get if you echo $sql; ?

Two ways to do it:

Code: Select all

$sql = "SELECT * FROM `Catalog` WHERE title = '{$article['alsolike']}'";
$sql = "SELECT * FROM `Catalog` WHERE title = '" . $article['alsolike'] . "'";

Re: Variable in SQL query

Posted: Mon Jan 11, 2010 4:16 pm
by easinewe
The first line works. Thanks! So I guess I just needed to use the curly braces around the variable.

So I can learn from this could you tell me how do the curly braces change how the variable is handled?

Re: Variable in SQL query

Posted: Mon Jan 11, 2010 7:12 pm
by SidewinderX
Variables in your SQL query behave in the same manner as variables in strings you echo. See here for a complete explanation: http://www.php.net/manual/en/language.t ... ng.parsing