Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

sql

php

hello every one i want to convert my array into other array type , plz help me out . I m using this

$row = mysql_fetch_array($result, MYSQL_ASSOC); 

and output is

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

but i want the the output 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 i should us to get the array in this format

like image 836
umar Avatar asked Mar 18 '11 15:03

umar


People also ask

How do I store SQL query results in an array?

You can't get a multi-dimensional array from the resultset of your SQL query in just one command. You need to repeat the function mysql_fetch_array once per SQL result row. Also you can use mysql_fetch_assoc to get the results as an associative array.

How do I save an array of objects in SQL database?

First, create a table called example with the following SQL statement: CREATE TABLE example ( `id` int NOT NULL AUTO_INCREMENT, `docs` JSON, PRIMARY KEY (`id`) ); The example table will have two columns: the id column and the docs column. And that's the easiest way you can store an array type using MySQL.

How can we fetch data from database and store in array in PHP?

Data can be fetched from MySQL tables by executing SQL SELECT statement through PHP function mysql_query. You have several options to fetch data from MySQL. The most frequently used option is to use function mysql_fetch_array(). This function returns row as an associative array, a numeric array, or both.


2 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 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).

like image 72
Brad Christie Avatar answered Oct 13 '22 01:10

Brad Christie


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);
like image 25
mravey Avatar answered Oct 12 '22 23:10

mravey