問題描述
$sql = "SELECT * FROM table WHERE id LIKE CONCAT('%', :id, '%')
LIMIT :limit1, :limit2";
我仍然想像這樣使用數組輸入:
I want to still use the array input like this:
$stmt->execute($array);
否則我無法重復使用相同的方法來執行我的查詢.
Otherwise I cannot reuse the same method for executing my queries.
同時,:limit1 和 :limit2 不起作用,除非像這樣輸入:
At the same time, the :limit1 and :limit2 doesn't work unless it is put in like this:
$stmt->bindParam(':limit1', $limit1, PDO::PARAM_INT);
我嘗試兩者都做,但它沒有使用 bindParams 執行:
I tried to do both but it doesn't execute with the bindParams:
$stmt->bindParam(':limit2', $limit2, PDO::PARAM_INT);
$stmt->execute($array);
有什么方法可以解決?
我想我可以擴展 PDOStatement 并添加一個新方法bindLimit"或其他東西,但我無法弄清楚 PDO 使用什么內部方法將參數綁定到變量.
I thought I could extend PDOStatement and add a new method "bindLimit" or something but I can't figure out what internal method PDO uses to bind parameters to a variable.
推薦答案
如果您關閉 PDO::ATTR_EMULATE_PREPARES
的默認設置,那么它就會起作用.我剛剛發現該設置默認為 mysql 啟用,這意味著您實際上從未使用過準備好的語句,php 在內部為您創建動態 sql,為您引用值并替換占位符.是的,一個主要的wtf.
If you turn off the default setting of PDO::ATTR_EMULATE_PREPARES
, then it will work. I just found out that that setting is on by default for mysql, which means you never actually use prepared statements, php internally creates dynamic sql for you, quoting the values for you and replacing the placeholders. Ya, a major wtf.
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$stmt = $pdo->prepare($sql);
$stmt->execute(array(5)); //works!
由于性能原因,默認情況下會模擬準備.
The prepares are emulated by default because of performance reasons.
另見PDO MySQL:使用PDO::ATTR_EMULATE_PREPARES 與否?
這篇關于如何傳遞 PDO 參數數組但仍指定它們的類型?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!