PHP / PDO: Prepared statements do not work when creating a table?

When I use a prepared PDO statement and use it to connect a table name to a query that it fails, a quick example:

$stmt = $dbh->prepare("CREATE TABLE ? (id foo, int bar,...)"); $stmt->execute(Array('table_foobar')); 

Does everything he does replace ? on 'table_foobar' , single quotes do not allow you to create a table for me!

I need to do sprintf at the top of the prepared statement to add to the predefined table name.

What am I missing here?

+4
source share
2 answers

I cannot find anything clear in the manual, but looking at user notes, the use of parameters is intended only for actual values, and not for table names, field names, etc.

Normal string concatenation should (and can) be used.

 $tablename = "tablename"; $stmt = $dbh->prepare("CREATE TABLE `$tablename` (id foo, int bar,...)"); 
+9
source

If you create the table dynamically, this most likely means that you do not understand the ideology of relational databases and, as a result, something is wrong. Just create all the tables when you configure the application from the finished dump and do not create any tables at run time.

No need to use a dynamic table name at all.

0
source

All Articles