問題描述
當我使用 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,...)");
這篇關于PHP/PDO:創建表時準備好的語句不起作用?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!