[英]How to get values in one column where another column equals a value with SQL, and store into an array in PHP?
Here is my table: 这是我的桌子:
user_id | group_id
------------------
1 | 22
2 | 22
3 | 22
4 | 1
5 | 1
I only want to get the user_id's from the group_id 22 and store them into an array. 我只想从group_id 22中获取user_id并将其存储到数组中。
My code in PHP: 我在PHP中的代码:
$group_id=22;
$user_ids_ar = mysqli_fetch_array($db->query("SELECT user_id FROM table WHERE group_id=".$group_id.";"), MYSQLI_NUM);
It only seems to return one value instead of the expected 3. How can I solve this? 它似乎只返回一个值,而不是预期的3。如何解决此问题?
You are only getting one row returned because you are only asking for one row. 您只返回一行,因为您只要求一行。 You need to loop over the fetch to get them all. 您需要遍历获取以获取所有内容。
$group_id=22;
$result = $db->query("SELECT user_id FROM table WHERE group_id=".$group_id);
while ( $row = mysqli_fetch_array($result, MYSQLI_NUM) ) {
$user_ids_ar[] = $row;
}
Or you could use fetchAll in the form you were using. 或者,您可以按使用的形式使用fetchAll。
$group_id=22;
$user_ids_ar = mysqli_fetch_all(
$db->query("SELECT user_id
FROM table
WHERE group_id=".$group_id)
, MYSQLI_NUM);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.