Variable in SQL query

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
easinewe
Forum Newbie
Posts: 23
Joined: Mon Jan 11, 2010 3:22 pm

Variable in SQL query

Post 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!
User avatar
AbraCadaver
DevNet Master
Posts: 2572
Joined: Mon Feb 24, 2003 10:12 am
Location: The Republic of Texas
Contact:

Re: Variable in SQL query

Post 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'] . "'";
mysql_function(): WARNING: This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQLextension should be used. See also MySQL: choosing an API guide and related FAQ for more information.
easinewe
Forum Newbie
Posts: 23
Joined: Mon Jan 11, 2010 3:22 pm

Re: Variable in SQL query

Post 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?
SidewinderX
Forum Contributor
Posts: 407
Joined: Fri Jul 16, 2004 9:04 pm
Location: NY

Re: Variable in SQL query

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