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

}
link|improve this question

feedback

4 Answers

up vote 9 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.

link|improve this answer
2  
You're too fast man! ;) – AlienWebguy Jul 19 '11 at 1:46
@AlienWebguy: Cheers. :) – alex Jul 19 '11 at 1:47
feedback

This will do the trick:

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

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.

link|improve this answer
feedback

Alternatively you can use my function to do that:

/**
 * traversing data set of a particular SELECT request as an associative array
 * @author Kirill "Nemoden" K.
 *
 * @param resourceId $resQ mysql resource Id to retreive data
 * @param string field field-identifier to be resulting array's key
 * @return array if data has been retreived. False otherwise
 */
function mysqlResourceReader($resQ, $field = '') {
    $result = array();
    $i=0;
  while ($r=mysql_fetch_array($resQ, MYSQL_ASSOC)){
    $keys = array_keys($r);
    foreach ($keys as $key) {
      if (!(bool)$field) {
        $result[$i][$key] = $r[$key];
      }
      else {
        if (!array_key_exists($r[$field], $result)) {
          $result[$r[$field]] = array();
        }
        if ($field != $key) {
          $result[$r[$field]][$key] = $r[$key];
        }
      }
    }
    $i++;
  }
    return empty($result) ? false : $result;
}

Usage:

$result = mysql_query("SELECT * FROM `Departments`");
$data = mysqlResourceReader($result);
// or $data = mysqlResourceReader($result, 'id');

Pretty handy.

link|improve this answer
feedback

Your Answer

 
or
required, but never shown

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