Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fetch all IDs and put them into an array in PHP

Tags:

php

mysql

How do I get a SQL script to collect all the IDs from a field and put them in an array?

like image 463
user663049 Avatar asked Mar 17 '11 20:03

user663049


1 Answers

If we assume that the ID column is just called id, then try the following code (DB connection code ommitted for clarity):

$ids_array = array();

$result = mysql_query("SELECT id FROM table_name");

while($row = mysql_fetch_array($result))
{
    $ids_array[] = $row['id'];
}

If you want to sort the IDs ascending or descending, simply add ORDER BY id ASC or ORDER BY id DESC respectively to the end of the MySQL query

What the code above does is iterate through every row returned by the query. $row is an array of the current row, which just contains id, because that's all we're selecting from the database (SELECT id FROM ...). Using $ids_array[] will add a new element to the end of the array you're storing your IDs in ($ids_array, and will have the value of $row['id'] (the ID from the current row in the query) put into it.

After the while loop, use print_r($ids_array); to see what it looks like.

like image 123
Bojangles Avatar answered Oct 31 '22 09:10

Bojangles