简体   繁体   English

PHP / MySQL-如何从表中选择ID并在数组中回显

[英]PHP/MySQL - How to select id from table and echo in array

How to make the array of id that we call from a table? 如何使我们从表中调用的ID数组?

What I want is like this : 我想要的是这样的:

$array = array(1, 2, 3, 4, 5); // **1 - 5 select from a table**.

Thank you 谢谢

Code : 代码:

$query = mysqli_query($conn, "SELECT * FROM tableA");
while($row = mysqli_fetch_assoc($query )){          
    $a = implode(',',(array)$row['id_add_user']);
    echo $a;
}

What I get from echo $a is 12345 not 1,2,3,4,5 我从echo $a得到echo $a12345而不是1,2,3,4,5

Add all the elements to an array, then implode() it into one string with your desired deliminator (here, its ", " ) once all results are fetched. 将所有元素添加到数组中,然后在获取所有结果后", "使用所需的分隔符(此处为", " )将其implode()成一个字符串。

$result = [];
$query = mysqli_query($conn, "SELECT * FROM tableA");
while($row = mysqli_fetch_assoc($query)){          
    $result[] = $row['id_add_user']);
}

echo implode(", ", $result);

Collect necessary values into an array. 将必要的值收集到数组中。

$a = [];
while(...){          
    $a[] = $row['id_add_user'];
}
echo implode(',', $a);

You are trying to implode() the values for each row, you need to build an array of all the values and then output the result implode d. 您尝试对每行的值进行implode()运算,需要构建所有值的数组,然后输出结果implode d。 Also if you just want one column - just fetch that column in your SQL 另外,如果您只想要一列-只需在SQL中获取该列

You can further simplify it to... 您可以进一步简化为...

$query = mysqli_query($conn, "SELECT id_add_user FROM tableA");
$rows = mysqli_fetch_all($query );
echo implode(',',array_column($rows, 'id_add_user' ));

mysqli_fetch_all allows you to fetch all the data in one go. mysqli_fetch_all允许您mysqli_fetch_all获取所有数据。 Then use array_column() to extract the data. 然后使用array_column()提取数据。

$array = array(1,2,3,4,5);

Use below SQL query for selecting the array id data 使用下面的SQL查询选择阵列ID数据

SELECT column_name(s)
FROM table_name
WHERE column_name IN $array;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM