Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Populate PHP Array from While Loop

Tags:

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)) {  } 
like image 963
JosephD Avatar asked Jul 19 '11 01:07

JosephD


People also ask

How can we store values from while loop into an array in PHP?

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);

How do you make an array while loop?

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.


2 Answers

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.

like image 94
alex Avatar answered Oct 11 '22 13:10

alex


This will do the trick:

$rows = array(); $result = mysql_query("SELECT * FROM `Departments`"); while($row = mysql_fetch_assoc($result)) {   $rows[] = $row; } 
like image 35
squinlan Avatar answered Oct 11 '22 14:10

squinlan