7dr3am7
7dr3am7

Reputation: 765

Php query into json

I am querying my database Select * from Customer the customer tables holds Name,Surname Address,age.

I want to be able to transform the query into a json object in the following object:

Customer:

[
    {Name:"john", Surname:"Beta" ,Age:"23"},
    {Name:"Fred", Surname:"alpha" ,Age:"31"}
];

Do you have any ideas?I tried to loop through the query and use merge_array.. but it MERGED the array as expected... Thank you for your time.

Upvotes: 2

Views: 8612

Answers (4)

user1648334
user1648334

Reputation:

Because I am using PDO to handle database calls I used a foreach statement.

$grids = $db->run("DATABASE QUERY");

foreach ($grids as $row) {
    $grid[] = $row;
}

$struct = array("Grid" => $grid);
print json_encode($struct);

Otherwise same code as above. Thanks Mario.

Upvotes: 0

mario
mario

Reputation: 145492

You just need to group into the expected nested structure:

while ($row = mysql_fetch_assoc($r)) {
    $customer[] = $row;
}

$struct = array("Customer" => $customer);
print json_encode($struct);

Upvotes: 6

Konerak
Konerak

Reputation: 39773

Either use it yourself, or have a look at what MySQL to JSON is doing and implement something like it :)

Upvotes: 1

NDM
NDM

Reputation: 6840

If you have code like this:

$sql = "SELECT id as userid, fullname, userstatus 
        FROM   sometable
        WHERE  userstatus = 1";
$result = mysql_query($sql);

seems like json_encode(mysql_fetch_assoc($result)); would do the job? Put in a foreach/while for all results...

Upvotes: 2

Related Questions