Connecting Tech Pros Worldwide Forums | Help | Site Map

Variable as tablename in query

Newbie
 
Join Date: Jun 2007
Posts: 1
#1: Jun 21 '07
I have a query that looks like this:

mysql_query("UPDATE layer1108 SET `set` = '$set', `order` = '$i' WHERE `item` = '$item' $col_check");

And it works the way I want, but I want the layer1108 to be dynamic. I have tried declaring this ahead of time and then putting that variable in. This doesn't work:

mysql_query("UPDATE $layerID SET `set` = '$set', `order` = '$i' WHERE `item` = '$item' $col_check");

But when I do this it works:

$dynamic_table_name = "layout1108";
mysql_query("UPDATE $dynamic_table_name SET `set` = '$set', `order` = '$i' WHERE `item` = '$item' $col_check");

But it doesn't work when I again make the "layout1108" a $layoutID variable.

Any thoughts on how to get this to work?

Lives Here
 
Join Date: Sep 2006
Posts: 12,070
#2: Jun 21 '07

re: Variable as tablename in query


Quote:

Originally Posted by inaz4sun

I have a query that looks like this:

mysql_query("UPDATE layer1108 SET `set` = '$set', `order` = '$i' WHERE `item` = '$item' $col_check");

And it works the way I want, but I want the layer1108 to be dynamic. I have tried declaring this ahead of time and then putting that variable in. This doesn't work:

mysql_query("UPDATE $layerID SET `set` = '$set', `order` = '$i' WHERE `item` = '$item' $col_check");

But when I do this it works:

$dynamic_table_name = "layout1108";
mysql_query("UPDATE $dynamic_table_name SET `set` = '$set', `order` = '$i' WHERE `item` = '$item' $col_check");

But it doesn't work when I again make the "layout1108" a $layoutID variable.

Any thoughts on how to get this to work?

This looks like a problem in your PHP code. The only difference between when you use $dynamic_table_name and when you use $layerID is the variable name, now since both are valid PHP identifiers, the problem must be with the value that you are setting when you use $layerID. How are you assigning values to it and what is the error that you're getting when you run it?
pbmods's Avatar
Site Moderator
 
Join Date: Apr 2007
Location: Texas
Posts: 5,435
#3: Jun 22 '07

re: Variable as tablename in query


Heya, inaz4sun.

Quote:

Originally Posted by inaz4sun

But it doesn't work when I again make the "layout1108" a $layoutID variable.

What do you mean by 'it doesn't work'? Try echoing the output of mysql_error().

Also, it would probably be a good idea to enclose your table name in backticks, just so that if something is wrong with the value of $dynamic_table_name, your queries will just fail instead of (potentially) doing something destructive:

Expand|Select|Wrap|Line Numbers
  1. $dynamic_table_name = "layout1108";
  2. mysql_query("UPDATE `$dynamic_table_name` SET `set` = '$set', `order` = '$i' WHERE `item` = '$item' $col_check");
  3.  
Reply