Getting a database record set to an array in php

I want to get a recordset from a MySQL table as an array.

So far, I have managed to get each row as an associative array. But I want all the rows in one array, because I have to access this full object in jQuery in order to display them.

This is what I have done so far. This is my .php script to retrieve data

//select query $result = mysql_query("SELECT * FROM student",$con) or die (mysql_error()); $numRows = mysql_num_rows($result); //to iterate the for loop //passing as an associative array for ($count = 0; $count < $numRows; $count++){ $row = mysql_fetch_array($result, MYSQL_ASSOC); echo json_encode($row); } 

This is what I'm getting right now

 {"StuId":"1","fName":"Saman","lName":"Kumara","age":"14","grade":"A"} {"StuId":"2","fName":"Marry","lName":"Vass","age":"12","grade":"B"} {"StuId":"3","fName":"Navjoth","lName":"Bogal","age":"32","grade":"A"} {"StuId":"4","fName":"Jassu","lName":"Singh","age":"22","grade":"E"} 

But I want this result to be set as follows.

 [ {"TEST1":45,"TEST2":23,"TEST3":"DATA1"}, {"TEST1":46,"TEST2":24,"TEST3":"DATA2"}, {"TEST1":47,"TEST2":25,"TEST3":"DATA3"} ] 

I am looking for help with this. Thanks in advance.

+4
source share
1 answer

Put everything in one array and then json_encode:

 $json = array( ); $result = mysql_query("SELECT * FROM student",$con) or die (mysql_error()); while( $row = mysql_fetch_assoc( $result ) ) { $json[] = $row; } echo json_encode( $json ); 

FYI: no need to count the number of results in a loop. mysql_fetch_ * will internally hold a pointer to the current record and increment it by each call. This makes it an ideal candidate for use in a simple loop. Alternatively, instead of mysql_fetch_array and passing MYSQL_ASSOC, you can simply use mysql_fetch_assoc, the method that I prefer. Makes the code easier to read (in my opinion, anyway).

+6
source

All Articles