简体   繁体   English

PHP / PDO:准备语句在创建表时不起作用?

[英]PHP/PDO: Prepared statements don't work when creating a table?

When I am using a PDO prepared statement, and use it to plug in a table name to the query it fails, a quick example: 当我使用PDO预处理语句,并使用它来插入查询失败的表名时,一个简单的例子:

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

All it does is replaces ? 它所做的只是替换? with 'table_foobar' , the single quotes don't allow creation of the table for me! 使用'table_foobar' ,单引号不允许为我创建表格!

I end up needing to do a sprintf on TOP of the prepared statement to add in a predefined table name. 我最终需要在预准备语句的TOP上执行sprintf以添加预定义的表名。

What on earth am I missing here? 我到底在这里错过了什么?

I can find nothing clear in the manual, but looking at the User Contributed Notes, the use of parameters is intended for actual values only, not 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,...)");

If you are creating a table dynamically, that most likely means you do not understand relational database ideology and as a result doing something wrong. 如果要动态创建表,这很可能意味着您无法理解关系数据库的意识形态,从而导致出错。
Just create all the tables at application setup from ready made dump and do not create any tables at runtime. 只需在现成的转储中创建应用程序设置中的所有表,并且不要在运行时创建任何表。

No need to use dynamic table name at all. 根本不需要使用动态表名。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM