問題描述
我正在使用準備好的語句將一些舊代碼移至新的 msqli 接口,我在處理包含 IN 子句的 SQL 語句時遇到問題.我通常會這樣做:
I’m moving some old code over to the new msqli interface using prepared statements, I’m having trouble with SQL statements containing the IN clause. I would just normally do this:
$ids = '123,535,345,567,878'
$sql = "SELECT * FROM table WHERE id IN ($ids)";
$res = mysql_query($sql);
將其轉換為 mysqli 和準備好的語句我嘗試了多種解決方案:
Converting this to mysqli and prepared statements I have tried a number of solutions:
$ids = '123,535,345,567,878'
$ids = implode($ids,',');
$result = $msqli->prepare("SELECT foo,blar FROM table WHERE id IN (?));
$result->bind_param("i", $ids);
$result->execute();
以上失敗,計算數組中的元素數和更改 SQL 字符串中問號的數量以及為數組中的每個元素調用 bind_parm 也失敗.僅使用逗號分隔的字符串也會失敗.
The above fails and calculating the number of elements in the array and altering number of question marks in the SQL string and calling bind_parm for each element in the array also fails. Just using the comma separated string also fails.
我在 Google 上找不到關于此的好的文檔,那么您是如何解決這個問題的?
I can find no good documentation in Google on this, so how have you solved the problem?
推薦答案
看這里之前有人問過的一個類似問題的答案(第二個代碼示例):
Look at the answer to a similar question that has been asked here before (second code sample):
我有一個整數數組,如何在 mysql 查詢中使用每個整數(在 php 中)?
歸結為:
- 創建帶有適量問號的 SQL 字符串
- 使用
call_user_func_array()
將數組綁定到查詢字符串
- create the SQL string with the right amount of question marks
- use
call_user_func_array()
to bind your array to the query string
這篇關于你如何在 mysqli 準備好的語句中使用 IN 子句的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!