問題描述
我想執行以下查詢:
選擇*,(SELECT COUNT(*) FROM `tab2` WHERE `parent` = :id) AS `sum`從`tab1`哪里`id` = :id
如您所見,:id
占位符在查詢中出現了兩次.因此,如果我嘗試使用以下命令執行此語句:
$q->execute(['id'=>$row_id]);
我收到錯誤:
致命錯誤:未捕獲的異常PDOException",消息為SQLSTATE[HY093]:參數編號無效
所以我必須重寫準備好的查詢并使用 :id1 和 :id2 占位符執行數組,這對我來說看起來有點愚蠢.
這是在準備好的語句的多個地方使用一個占位符的唯一方法嗎?
PDO::prepare 表示
<塊引用>[y]你不能在準備好的語句中多次使用同名的命名參數標記,除非模擬模式打開.
由于通常最好關閉仿真模式(因此數據庫執行準備好的語句),因此您必須使用 id_0
、id_1
等>
I'd like to perform the following query:
SELECT *, (SELECT COUNT(*) FROM `tab2` WHERE `parent` = :id) AS `sum` FROM `tab1` WHERE `id` = :id
As you can see :id
placeholder appeared twice in the query. So if I'd try to execute this statement with:
$q->execute(['id'=>$row_id]);
I'm receiving the error:
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY093]: Invalid parameter number
So I have to rewrite the prepared query and execute array with :id1 and :id2 placeholders which looks a bit stupid for me.
Is it the only way to use one placeholder in several places of the prepared statement?
PDO::prepare states that
[y]ou cannot use a named parameter marker of the same name more than once in a prepared statement, unless emulation mode is on.
Since it's generally better to leave emulation mode off (so the database does the prepared statement), you'll have to use id_0
, id_1
, etc.
這篇關于PHP 的 PDO 準備語句:我可以多次使用一個占位符嗎?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!