将变量插入到从PHP变量名称中选择的表中

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.

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')");

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 !

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')"
                     );