Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieving a database record set into an array in php

I want to retrieve a set of records from a MySQL table as an array.

So far I was able to retrieve each row as an associative array. But I want all the rows in one array because I have to access that complete object in jQuery 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 currently get

{"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 set as follows.

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

I seek help in doing this. Thanks in advance.

like image 316
SriniShine Avatar asked May 31 '11 08:05

SriniShine


1 Answers

Put it all in one array, then json_encode it:

$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: there's no need to count the number of results to loop. mysql_fetch_* will internally keep a pointer to the current record and increment that on each call. That makes it a perfect candidate to use in a simple while loop. Also, instead of mysql_fetch_array and passing MYSQL_ASSOC, you can simply use mysql_fetch_assoc instead, a method I much prefer. Makes the code easier to read too (in my opinion, anyway).

like image 105
Berry Langerak Avatar answered Sep 20 '22 06:09

Berry Langerak