Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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

}
share|improve this question

3 Answers

up vote 17 down vote accepted

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.

share|improve this answer
2  
You're too fast man! ;) – AlienWebguy Jul 19 '11 at 1:46

This will do the trick:

$rows = array();
$result = mysql_query("SELECT * FROM `Departments`");
while($row = mysql_fetch_assoc($result))
{
  $rows[] = $row;
}
share|improve this answer

This has been one of the fastest ways for me to create (multi-dimensional) arrays. I'm not sure if you want all of your results smooshed into one array or not.

// Read records
$query = "SELECT * FROM `Departments`"; 
$query = mysql_query($query);

// Put them in array
for($i = 0; $array[$i] = mysql_fetch_assoc($query); $i++) ;

// Delete last empty one
array_pop($array);

You can use print_r($array) to see the results.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.