[英]zend framework: how to prepare and execute WHERE IN clause?
我想准備一個在循環內使用的語句。 當我嘗試執行該語句時,我在日志中看到一條錯誤消息,顯示“參數編號無效:未綁定參數”。
我的代碼有什么問題?
$itemSelectSql = "SELECT * FROM `tblItems` WHERE `itemID` IN (?)";
$itemSelectStmt = new Zend_Db_Statement_Mysqli($this->db_ro, $itemSelectSql);
while () {
...
$itemIds = array();
// populate $itemIds array
...
$itemSelectStmt->execute(array($itemIds));
}
編輯:
我想我的設置中可能有一個錯誤,這解釋了為什么我嘗試失敗的原因。 我看到了這個:
PHP Warning: call_user_func_array() expects parameter 1 to be a valid callback,
class 'PDOStatement' does not have a method 'bind_param' in
/var/www/lib/Zend/Db/Statement/Mysqli.php on line 204
編輯:
我使用了錯誤的適配器。 應該是 Zend_Db_Statement_Pdo :-)
感謝您的回復。
?
不能用數組替換,它必須用標量替換(感謝評論指出這並不總是意味着字符串......我的大腦放屁)。 讓我知道這是否效果更好:
$itemSelectSql = "SELECT * FROM `tblItems` WHERE `itemID` IN ";
while () {
...
$itemIds = array();
// populate $itemIds array
...
// we need to have the same number of "?,"'s as there are items in the array.
// and then remove final comma.
$qs = rtrim(str_repeat("?,", count($itemIds)),',');
// create a statement based on the result
$itemSelectStmt =
new Zend_Db_Statement_Mysqli($this->db_ro, "$itemSelectSql ($qs)");
// bind to each of those commas.
$itemSelectStmt->execute($itemIds);
}
您是否嘗試過這樣做:
while () {
...
$itemIds = array();
// populate $itemIds array
$itemIds = implode(',' $itemIds);
$itemSelectStmt->execute(array($itemIds));
}
我不是 Zend_framework 的專家,但是當你使用語句時,你必須
如果您使用位置參數,或那些標有問號 ('?') 的參數,請將綁定值傳遞到普通數組中。
所以我認為你需要傳遞一個帶有一個值的數組,並且該值替換“?” 在聲明中。 在這種情況下,您需要一個逗號分隔的字符串(如果您的 id 是 int)來替換語句中的 (?)。
如果您不內爆這些值,您所做的就是傳遞一個包含數組的數組。
您可以使用FIND_IN_SET(str,strlist)
而不是IN ()
:
mysql> select id, name from customer where find_in_set(id, '10,15,20');
+----+---------+
| id | name |
+----+---------+
| 10 | ten |
| 15 | fifteen |
| 20 | twelve |
+----+---------+
這樣,您不必將具有多個值的數組綁定到IN()
,您可以將 ID 列表作為單個逗號分隔的字符串傳遞。 您可以安全地使用 PHP function implode()
從 ID 數組生成字符串。
不過,我不確定它是否對性能有任何影響。 我查看了explain
的 output ,看起來find_in_set()
無法使用索引,因此生成具有可變數量參數的查詢應該會更好。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.