![](/img/trans.png)
[英]How to Make PHP/SQL Query to Select Rows Where Column Doesn't Equal Variable
[英]return rows where column in variable array in php and sql
我正在寫一個查詢,當其中一列的值與數組的任何元素匹配時將返回記錄。 如果我使用靜態數組,則可以正常工作(請參見示例):
sql = "SELECT *
FROM tasks
WHERE
tasks.type IN ('homework', 'chores', 'laundry')";
如果我有一系列要從比較中使用的用戶輸入中填充的任務怎么辦? 像這樣:
$task_list = //declaration and populate the array. I know it works, so I'm skipping it
sql = "SELECT *
FROM tasks
WHERE
tasks.type IN "+$task_list+" ";
這給我一個錯誤。 我真的不擅長將php與sql混合使用,並確實找到了答案……也許我無法正確搜索正確的語法。
對於那些想知道的人, var_dump($task_list);
打印以下內容:
array(3) { [0]=> string(8) "homework" [1]=> string(6) "chores" [2]=> string(7) "laundry" }
由於$ task_list是一個數組,因此失敗,您應該執行以下操作:
$task_list_str = sprintf('"%s"', implode('", "', $task_list));
$sql = 'SELECT *
FROM tasks
WHERE
tasks.type IN (' . $task_list_str . ')';
這有點令人費解,但是它與您的代碼保持盡可能的接近。
希望這可以幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.