tags:

views:

533

answers:

3

So, I want to insert some data into a MySQL table where the table name that the data is being put into is a PHP Variable.

Something like this:

$tablename = "databasetable";

$insert = mysql_query(
"INSERT INTO '".$tablename."' (column1, col2) 
VALUES ('Blah', 'Blah')
");

But that of course doesn't work, so I'm not sure what to do. By the way, I'm new to PHP and StackOverflow.

+2  A: 

Remove the single quotes from around the table name variable and it'll work:

$tablename = "databasetable";

$insert = mysql_query(
"INSERT INTO ".$tablename." (column1, col2) VALUES ('Blah', 'Blah')");
Doug Hays
this is the answer, however you (Neo) should read up on SQL injection, and learn how this could potentially ruin your database.
seanmonstar
Thanks for that. I have escaped the variables I'm inserting with mysql_real_escape_string();. I also discovered that I was parsing two strings that were being put together incorrectly, but now what I was doing works.
Neodarkleo
+1  A: 

What about :

$tablename = "databasetable";
$insert = mysql_query("INSERT INTO ".$tablename." (column1, col2) VALUES ('Blah', 'Blah')");

ie, without the simple quotes you were putting arround the table name.

Or, as you are using double-quoted string, which means variables are interpolated :

$tablename = "databasetable";
$insert = mysql_query("INSERT INTO $tablename (column1, col2) VALUES ('Blah', 'Blah')");

As a sidenote, in both cases, you must be really sure that $tablename doesn't contain any malicious data !

Pascal MARTIN
A: 

My answer is similar to Doug's, although I would use 'back-ticks' in the query around the table name to distinguish it as a table as further prevent the possibility of malicious injection...

E.g.

$tablename = "databasetable";

$insert = mysql_query("INSERT INTO `{$tablename}` (column1, col2) 
                         VALUES ('Blah', 'Blah')"
                     );
Dave Rix