If I am fetching data from a MySQL database and using a while loop to iterate through the data how would I add each one to array?
$result = mysql_query("SELECT * FROM `Departments`"); while($row = mysql_fetch_assoc($result)) { }
Show activity on this post. I would like to store value from while loop but not in multidimensional way : $movies_id = array(); while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) { $id = $row['id']; $title_id = $row['title_id']; $movies_id[] = [$id => $title_id]; } print_r($movies_id);
All you have to do is initialize the index that points to last element of the array, decrement it during each iteration, and have a condition that index is greater than or equal to zero. In the following program, we initialize an array, and traverse the elements of array from end to start using while loop.
Build an array up as you iterate with the while
loop.
$result = mysql_query("SELECT * FROM `Departments`"); $results = array(); while($row = mysql_fetch_assoc($result)) { $results[] = $row; }
Alternatively, if you used PDO, you could do this automatically.
This will do the trick:
$rows = array(); $result = mysql_query("SELECT * FROM `Departments`"); while($row = mysql_fetch_assoc($result)) { $rows[] = $row; }
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