View Full Version : Concatenating a variable into sql

11-21-2010, 06:20 AM
hello again,

I am trying to figure this out, but sometimes it just doesn't work for me. and I have no idea why. I'm getting:
you have an error in your sql syntax near 'desc FROM names WHERE thename = 'adam'' at line 1obviously the criteria is not quoted correctly, but I simply don't get it. Here's the query:
$query2 = "SELECT thename, desc FROM names

WHERE thename = '" . $tempname . "'" or die(mysql_error());Isn't that the way you're supposed to concat strings into the statement? That's the way you do it in visual basic, and anything else I've ever worked with.

Similarly, I have the exact same query, with different variables only, running earlier in the script and it has the same concat syntax. That was does NOT kill the script, so apparently it works. What am I missing here guys?

11-21-2010, 06:57 AM
not sure if your code was as-is but it looks like "or die(etc" was part of your query ?
anyway, use backticks for field and table names to avoid mysql confusion and you can use braces around your variables to avoid further confusion

$sql="SELECT `thename`, `desc` FROM `names` WHERE `thename` = '{$tempname}' ";
mysql_query($sql)or die(mysql_error());

(edit) and if you have to concatenate ...
$sql="SELECT `thename`, `desc` FROM `names` WHERE `thename` = '".$tempname."'";

11-21-2010, 07:13 AM
putting tick marks around the field names did it. thank you. I don't have a list of reserved words for PHP, and I'm sure that was the problem. 'desc' is obviously reserved and I should have seen that. Sorry about that! I think I need to fix my naming conventions as well. :rolleyes:

11-22-2010, 06:54 AM
I rather suspect "names" to be the reserved SQL word (cf. SET NAMES UTF8)