如何用数组查询数据库?在哪里='array()' [英] How to query a database with an array? WHERE = 'array()'
问题描述
我想知道如何使用数组查询数据库,就像这样:
I'm wondering how to query a database using an array, like so:
$query = mysql_query("SELECT * FROM status_updates WHERE member_id = '$friends['member_id']'");
$ friends
是一个数组,其中包含会员编号。我正在尝试查询数据库并显示所有结果,其中 member_id
等于 $ friends
数组。
$friends
is an array which contains the member's ID. I am trying to query the database and show all results where member_id
is equal to one of the member's ID in the $friends
array.
是否可以执行类似 WHERE = $ friends [member_id]
的方法?将数组转换成字符串并像这样构建查询:
Is there a way to do something like WHERE = $friends[member_id]
or would I have to convert the array into a string and build the query like so:
$query = "";
foreach($friends as $friend){
$query .= 'OR member_id = '.$friend[id.' ';
}
$query = mysql_query("SELECT * FROM status_updates WHERE member_id = '1' $query");
任何帮助将不胜感激!
推荐答案
您要 IN
。
SELECT * FROM status_updates WHERE member_id IN ('1', '2', '3');
因此代码更改为:
$query = mysql_query("SELECT * FROM status_updates WHERE member_id IN ('" . implode("','", $friends) . "')");
依赖于friends数组中数据的来源,许多人希望每个值都通过 mysql_real_escape_string()
以确保没有SQL注入。
Depending on where the data in the friends array comes from you many want to pass each value through mysql_real_escape_string()
to make sure there are no SQL injections.
这篇关于如何用数组查询数据库?在哪里='array()'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!