How do I get a SQL script to collect all the IDs from a field and put them in an array?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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 ASCorORDER BY id DESCrespectively to the end of the MySQL queryWhat the code above does is iterate through every row returned by the query.
$rowis an array of the current row, which just containsid, 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.