簡體   English   中英

PHP / MySQL-如何從表中選擇ID並在數組中回顯

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

如何使我們從表中調用的ID數組?

我想要的是這樣的:

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

謝謝

代碼:

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

我從echo $a得到echo $a12345而不是1,2,3,4,5

將所有元素添加到數組中,然后在獲取所有結果后", "使用所需的分隔符(此處為", " )將其implode()成一個字符串。

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

echo implode(", ", $result);

將必要的值收集到數組中。

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

您嘗試對每行的值進行implode()運算,需要構建所有值的數組,然后輸出結果implode d。 另外,如果您只想要一列-只需在SQL中獲取該列

您可以進一步簡化為...

$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允許您mysqli_fetch_all獲取所有數據。 然后使用array_column()提取數據。

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

使用下面的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