Populate PHP Array from While Loop

JosephD picture JosephD · Jul 19, 2011 · Viewed 94k times · Source

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

}

Answer

alex picture alex · Jul 19, 2011

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.