How to save all the results of a SQL query in a multidimensional array?

Hi everyone, I want to convert my array to another type of array, plz help me. i m using this

$row = mysql_fetch_array($result, MYSQL_ASSOC); 

and conclusion

 Array ( [user_id] => 250 [name] => a [age] => sfsf [pic_path] => ) 

but I want the result in this format

 Array ( [0] => Array ( [user_id] => 250 [name] => a [age] => sfsf [pic_path] => ) [1] => Array ( [user_id] => 251 [name] => b [age] => sfsfs [pic_path] => ) ) 

so what function should I get an array in this format

+6
sql php
source share
5 answers
 $data = array(); // create a variable to hold the information while (($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 February '17 Now that he is 2017, he says that you are using PDO through mysql_ *. It is much safer and can return this using fetchAll (as shown in TrexXx's answer).

+14
source share

The only way to avoid the loop is to use PDO (http://fr2.php.net/manual/fr/book.pdo.php), which is the best way to access the database in PHP, and you could do this:

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

If you need to keep all the rows returned by the request in an array, try the following:

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

You should usually assign these results in a loop.

 $rows = array(); while ($result = mysql_fetch_array($result, MYSQL_ASSOC)) { $rows[] = $result; } 
+1
source share

You cannot get a multidimensional array from the result set of your SQL query in just one command. You need to repeat the mysql_fetch_array function once per SQL result string.

You can also use mysql_fetch_assoc to get the results as an associative array.

To achieve your goal:

 $num = mysql_num_rows($result); for ($i = 0; $i < $num; $i++) { $myArray[] = mysql_fetch_assoc($result); } 
+1
source share

All Articles