How do I store all results from an SQL query in a multidimensional array? How do I store all results from an SQL query in a multidimensional array? sql sql

How do I store all results from an SQL query in a multidimensional array?


$data = array(); // create a variable to hold the informationwhile (($row = mysql_fetch_array($result, MYSQL_ASSOC)) !== false){  $data[] = $row; // add the row in to the results (data) array}print_r($data); // print result

Update Feb '17 Now that it's 2017, it's advised you use PDOs over mysql_*. A lot safer and can return this natively with fetchAll (as shown in `TrexXx's answer).


The only way to avoid doing a loop would to use PDO (PHP Data Objects) which is a better way to access database in PHP and you could do this :

$pdo = new PDO('mysql:host=localhost;dbname=test', 'root', '');    $q = $pdo->query('select * from yourtable');$r = $q->fetchAll();    var_dump($r);


If you need to store all rows returned by the query in an array, try this:

$result = array(); while ( $row = mysql_fetch_array($result, MYSQL_ASSOC) ){    $result[] = $row}