Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return JSON from MySQL with Column Name

I use PHP to fetch a row from MySQL and then encode it into JSON using the following code

$jsonData = array();
if(mysqli_num_rows($result) > 0){
while ($array = mysqli_fetch_row($result)) {
    $jsonData[] = $array;
}
$json = json_encode($jsonData);
echo stripslashes($json);
}`

However, I only get the the row values. I want rows values along with their column names. Currently it returns the following JSON.

[["shekhar","Shekhar Chatterjee","https://graph.facebook.com/1254850974526564/picture","0"]],[["shek","Shekhar Chatterjee","","0"]]

I would like to have the following output:

[{
  "user":"shekhar",
  "name":"Shekhar Chatterjee",
  "url":"https://graph.facebook.com/1254850974526564/picture",
  "stat":"0"
 },{
  "user":"shekhar",
  "name":"Shekhar Chatterjee",
  "url":"https://graph.facebook.com/1254850974526564/picture",
  "stat":"0"
}]
like image 828
Shekhar Chatterjee Avatar asked Jul 18 '16 12:07

Shekhar Chatterjee


3 Answers

Use mysqli_fetch_assoc()

Here you go

$jsonData = array();
if(mysqli_num_rows($result) > 0){
while ($array = mysqli_fetch_assoc($result)) {
    $jsonData[] = $array;
}
$json = json_encode($jsonData);
echo stripslashes($json);
}
like image 121
Saurabh Avatar answered Sep 21 '22 20:09

Saurabh


You should try while($row = mysqli_fetch_assoc($result)).

It should return the result with the respective fieldnames.

You can find the manual page here.

like image 21
PockeTiger Avatar answered Sep 23 '22 20:09

PockeTiger


You should use mysqli_fetch_assoc here instead so that it returns the key as the column names. mysqli_fetch_row returns numeric array keys instead.

Try this:

if (mysqli_num_rows($result) > 0) {
   $jsonData[] =  mysqli_fetch_assoc($result);
}
$json = json_encode($jsonData, JSON_PRETTY_PRINT);
like image 33
Object Manipulator Avatar answered Sep 25 '22 20:09

Object Manipulator