How do I get a SQL script to collect all the IDs from a field and put them in an array?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With