Link to home
Start Free TrialLog in
Avatar of evibesmusic
evibesmusicFlag for United States of America

asked on

What is the proper way to quote a variable used in a MySQL query?

Experts,

I made the mistake of naming some of my columns in my table with only numbers.

This is causing problems when trying to update the values in my table. I understand that I need to quote the column name but, I am going in circles.

Here's an example...the value of $template_id = 2

Here's my PHP query:

$update_template_matrix = "UPDATE db12.tblname SET ".$template_id."=1 WHERE id='".$id."'";

How do I quote the $template_id variable (which is a single digit) so that I can use it properly in this query?
ASKER CERTIFIED SOLUTION
Avatar of Dave Baldwin
Dave Baldwin
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Hey,

You need to use this character: `

So your query will become:
$update_template_matrix = "UPDATE db12.tblname SET `".$template_id."` =1 WHERE id='".$id."'";

Open in new window


You can also do this:
$update_template_matrix = "UPDATE db12.tblname SET `$template_id` =1 WHERE id='$id'";

Open in new window


Let me know if either of the two don't work.

best,
Shishir S.
Avatar of evibesmusic

ASKER

@DaveBaldwin:

What keyboard strokes do you use to produce the back-tick?
It's in the upper left corner of the US keyboard on the same key as ~ which is usually under the ESC key.
@DaveBaldwin:

Ahhh...yes...I've seen it many a times just never had a use for it until now.

Silly me for using a number-only naming convention for my table names...nothing like backtracking through a ton of code to fix this issue.

Thanks @DaveBaldwin!
Thanks!
You're welcome.  Note that many languages like javascript do not allow the first character of a variable name to be a number.