简体   繁体   English

如何在SQL中获取另一列等于值的一列中的值,并存储到PHP数组中?

[英]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.

相关问题 MySql 获取其中一列等于另一列等于另一表中的另一列的行 - MySql get rows where one column equals to another colum in another table where one column is equal PHP / MySQL-从另一列等于值的列中选择RANDOM值 - PHP/MySQL - Select RANDOM value from column where another column equals value SQL在一个列中计算最常用的值,其中另一列等于某值。 - SQL Count most used value in one column where other column equals something. 如何选择值等于的列? - How to select column where value equals? PHP获取数组中一列的值 - PHP get value of one column in array 验证值,其中记录的另一列的值位于值数组中 - Validate value where another column's value for the record is in array of values PHP PDO想从2列中获取值并创建数组(一个列值作为键,另一个列作为数组) - Php PDO want to fetch values from 2 columns and create array (one column value as key another as array) MySQL获取另一个表中所有行的计数,其中值等于当前表中的列 - MySQL get count of all rows in another table where the value equals column in current table 如何 select 基于 SQL/php 中另一列的多个值的列中的单个值 - How to select a single value from a column based on multiple values from another column in SQL/php 选择列等于另一个查询的任何值的位置 - Select where a column equals any value from another query
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM