問(wèn)題描述
我想執(zhí)行以下查詢:
選擇*,(SELECT COUNT(*) FROM `tab2` WHERE `parent` = :id) AS `sum`從`tab1`哪里`id` = :id
如您所見(jiàn),:id
占位符在查詢中出現(xiàn)了兩次.因此,如果我嘗試使用以下命令執(zhí)行此語(yǔ)句:
$q->execute(['id'=>$row_id]);
我收到錯(cuò)誤:
致命錯(cuò)誤:未捕獲的異常PDOException",消息為SQLSTATE[HY093]:參數(shù)編號(hào)無(wú)效
所以我必須重寫準(zhǔn)備好的查詢并使用 :id1 和 :id2 占位符執(zhí)行數(shù)組,這對(duì)我來(lái)說(shuō)看起來(lái)有點(diǎn)愚蠢.
這是在準(zhǔn)備好的語(yǔ)句的多個(gè)地方使用一個(gè)占位符的唯一方法嗎?
PDO::prepare 表示
<塊引用>[y]你不能在準(zhǔn)備好的語(yǔ)句中多次使用同名的命名參數(shù)標(biāo)記,除非模擬模式打開(kāi).
由于通常最好關(guān)閉仿真模式(因此數(shù)據(jù)庫(kù)執(zhí)行準(zhǔn)備好的語(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.
這篇關(guān)于PHP 的 PDO 準(zhǔn)備語(yǔ)句:我可以多次使用一個(gè)占位符嗎?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!