PHP/PDO:创建表时准备好的语句不起作用?
当我使用 PDO 准备好的语句,并使用它插入表名到查询失败时,一个简单的例子:
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:
$stmt = $dbh->prepare("CREATE TABLE ? (id foo, int bar,...)");
$stmt->execute(Array('table_foobar'));
它所做的只是将 ?
替换为 'table_foobar'
,单引号不允许为我创建表!
All it does is replaces ?
with 'table_foobar'
, the single quotes don't allow creation of the table for me!
我最终需要在准备好的语句的顶部执行 sprintf
以添加预定义的表名.
I end up needing to do a sprintf
on TOP of the prepared statement to add in a predefined table name.
我到底错过了什么?
推荐答案
我在手册中找不到任何明确的内容,但是查看用户贡献的注释,参数的使用是针对实际值仅,不包括表名、字段名等
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,...)");
相关文章