[php] JSON encode MySQL results

How do I use the json_encode() function with MySQL query results? Do I need to iterate through the rows or can I just apply it to the entire results object?

This question is related to php mysql json

The answer is


When using PDO

Use fetchAll() to fetch all rows as an associative array.

$stmt = $pdo->query('SELECT * FROM article');
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($rows);

When your SQL has parameters:

$stmt = $pdo->prepare('SELECT * FROM article WHERE id=?');
$stmt->execute([1]);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($rows);

When you need to rekey the table you can use foreach loop and build the array manually.

$stmt = $pdo->prepare('SELECT * FROM article WHERE id=?');
$stmt->execute([1]);

$rows = [];
foreach ($stmt as $row) {
    $rows[] = [
        'newID' => $row['id'],
        'Description' => $row['text'],
    ];
}

echo json_encode($rows);

When using mysqli

Use fetch_all() to fetch all rows as an associative array.

$res = $mysqli->query('SELECT * FROM article');
$rows = $res->fetch_all(MYSQLI_ASSOC);
echo json_encode($rows);

When your SQL has parameters you need to perform prepare/bind/execute/get_result.

$id = 1;
$stmt = $mysqli->prepare('SELECT * FROM article WHERE id=?');
$stmt->bind_param('s', $id); // binding by reference. Only use variables, not literals
$stmt->execute();
$res = $stmt->get_result(); // returns mysqli_result same as mysqli::query()
$rows = $res->fetch_all(MYSQLI_ASSOC);
echo json_encode($rows);

When you need to rekey the table you can use foreach loop and build the array manually.

$stmt = $mysqli->prepare('SELECT * FROM article WHERE id=?');
$stmt->bind_param('s', $id);
$stmt->execute();
$res = $stmt->get_result();

$rows = [];
foreach ($res as $row) {
    $rows[] = [
        'newID' => $row['id'],
        'Description' => $row['text'],
    ];
}

echo json_encode($rows);

When using mysql_* API

Please, upgrade as soon as possible to a supported PHP version! Please take it seriously. If you need a solution using the old API, this is how it could be done:

$res = mysql_query("SELECT * FROM article");

$rows = [];
while ($row = mysql_fetch_assoc($res)) {
    $rows[] = $row;
}

echo json_encode($rows);

$array = array();
$subArray=array();
$sql_results = mysql_query('SELECT * FROM `location`');

while($row = mysql_fetch_array($sql_results))
{
    $subArray[location_id]=$row['location'];  //location_id is key and $row['location'] is value which come fron database.
    $subArray[x]=$row['x'];
    $subArray[y]=$row['y'];


 $array[] =  $subArray ;
}
echo'{"ProductsData":'.json_encode($array).'}';

The code below works fine here!

<?php

  $con=mysqli_connect("localhost",$username,$password,databaseName);

  // Check connection
  if (mysqli_connect_errno())
  {
   echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

  $query = "the query here";

  $result = mysqli_query($con,$query);

  $rows = array();
  while($r = mysqli_fetch_array($result)) {
    $rows[] = $r;
  }
  echo json_encode($rows);

  mysqli_close($con);
?>

Thanks.. my answer goes:

if ($result->num_rows > 0) {
            # code...
            $arr = [];
            $inc = 0;
            while ($row = $result->fetch_assoc()) {
                # code...
                $jsonArrayObject = (array('lat' => $row["lat"], 'lon' => $row["lon"], 'addr' => $row["address"]));
                $arr[$inc] = $jsonArrayObject;
                $inc++;
            }
            $json_array = json_encode($arr);
            echo $json_array;
        }
        else{
            echo "0 results";
        }

$array = array();
$subArray=array();
$sql_results = mysql_query('SELECT * FROM `location`');

while($row = mysql_fetch_array($sql_results))
{
    $subArray[location_id]=$row['location'];  //location_id is key and $row['location'] is value which come fron database.
    $subArray[x]=$row['x'];
    $subArray[y]=$row['y'];


 $array[] =  $subArray ;
}
echo'{"ProductsData":'.json_encode($array).'}';

we could simplify Paolo Bergantino answer like this

$sth = mysql_query("SELECT ...");
print json_encode(mysql_fetch_assoc($sth));

Try this, this will create your object properly

 $result = mysql_query("SELECT ...");
 $rows = array();
   while($r = mysql_fetch_assoc($result)) {
     $rows['object_name'][] = $r;
   }

 print json_encode($rows);

http://www.php.net/mysql_query says "mysql_query() returns a resource".

http://www.php.net/json_encode says it can encode any value "except a resource".

You need to iterate through and collect the database results in an array, then json_encode the array.


Thanks.. my answer goes:

if ($result->num_rows > 0) {
            # code...
            $arr = [];
            $inc = 0;
            while ($row = $result->fetch_assoc()) {
                # code...
                $jsonArrayObject = (array('lat' => $row["lat"], 'lon' => $row["lon"], 'addr' => $row["address"]));
                $arr[$inc] = $jsonArrayObject;
                $inc++;
            }
            $json_array = json_encode($arr);
            echo $json_array;
        }
        else{
            echo "0 results";
        }

Code:

$rows = array();

while($r = mysqli_fetch_array($result,MYSQL_ASSOC)) {

 $row_array['result'] = $r;

  array_push($rows,$row_array); // here we push every iteration to an array otherwise you will get only last iteration value
}

echo json_encode($rows);

When using PDO

Use fetchAll() to fetch all rows as an associative array.

$stmt = $pdo->query('SELECT * FROM article');
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($rows);

When your SQL has parameters:

$stmt = $pdo->prepare('SELECT * FROM article WHERE id=?');
$stmt->execute([1]);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($rows);

When you need to rekey the table you can use foreach loop and build the array manually.

$stmt = $pdo->prepare('SELECT * FROM article WHERE id=?');
$stmt->execute([1]);

$rows = [];
foreach ($stmt as $row) {
    $rows[] = [
        'newID' => $row['id'],
        'Description' => $row['text'],
    ];
}

echo json_encode($rows);

When using mysqli

Use fetch_all() to fetch all rows as an associative array.

$res = $mysqli->query('SELECT * FROM article');
$rows = $res->fetch_all(MYSQLI_ASSOC);
echo json_encode($rows);

When your SQL has parameters you need to perform prepare/bind/execute/get_result.

$id = 1;
$stmt = $mysqli->prepare('SELECT * FROM article WHERE id=?');
$stmt->bind_param('s', $id); // binding by reference. Only use variables, not literals
$stmt->execute();
$res = $stmt->get_result(); // returns mysqli_result same as mysqli::query()
$rows = $res->fetch_all(MYSQLI_ASSOC);
echo json_encode($rows);

When you need to rekey the table you can use foreach loop and build the array manually.

$stmt = $mysqli->prepare('SELECT * FROM article WHERE id=?');
$stmt->bind_param('s', $id);
$stmt->execute();
$res = $stmt->get_result();

$rows = [];
foreach ($res as $row) {
    $rows[] = [
        'newID' => $row['id'],
        'Description' => $row['text'],
    ];
}

echo json_encode($rows);

When using mysql_* API

Please, upgrade as soon as possible to a supported PHP version! Please take it seriously. If you need a solution using the old API, this is how it could be done:

$res = mysql_query("SELECT * FROM article");

$rows = [];
while ($row = mysql_fetch_assoc($res)) {
    $rows[] = $row;
}

echo json_encode($rows);

Sorry, this is extremely long after the question, but:

$sql = 'SELECT CONCAT("[", GROUP_CONCAT(CONCAT("{username:'",username,"'"), CONCAT(",email:'",email),"'}")), "]") 
AS json 
FROM users;'
$msl = mysql_query($sql)
print($msl["json"]);

Just basically:

"SELECT" Select the rows    
"CONCAT" Returns the string that results from concatenating (joining) all the arguments
"GROUP_CONCAT" Returns a string with concatenated non-NULL value from a group

For example $result = mysql_query("SELECT * FROM userprofiles where NAME='TESTUSER' ");

1.) if $result is only one row.

$response = mysql_fetch_array($result);
echo json_encode($response);

2.) if $result is more than one row. You need to iterate the rows and save it to an array and return a json with array in it.

$rows = array();
if (mysql_num_rows($result) > 0) {
    while($r = mysql_fetch_assoc($result)) {
       $id = $r["USERID"];   //a column name (ex.ID) used to get a value of the single row at at time
       $rows[$id] = $r; //save the fetched row and add it to the array.
    }
}    
echo json_encode($rows);

I have the same requirement. I just want to print a result object into JSON format so I use the code below. I hope you find something in it.

// Code of Conversion
$query = "SELECT * FROM products;";
$result = mysqli_query($conn , $query);

if ($result) {
echo "</br>"."Results Found";

// Conversion of result object into JSON format
$rows = array();
while($temp = mysqli_fetch_assoc($result)) {
    $rows[] = $temp;
}
echo "</br>" . json_encode($rows);

} else {
    echo "No Results Found";
}

http://www.php.net/mysql_query says "mysql_query() returns a resource".

http://www.php.net/json_encode says it can encode any value "except a resource".

You need to iterate through and collect the database results in an array, then json_encode the array.


I have the same requirement. I just want to print a result object into JSON format so I use the code below. I hope you find something in it.

// Code of Conversion
$query = "SELECT * FROM products;";
$result = mysqli_query($conn , $query);

if ($result) {
echo "</br>"."Results Found";

// Conversion of result object into JSON format
$rows = array();
while($temp = mysqli_fetch_assoc($result)) {
    $rows[] = $temp;
}
echo "</br>" . json_encode($rows);

} else {
    echo "No Results Found";
}

I solved like this

$stmt->bind_result($cde,$v_off,$em_nm,$q_id,$v_m);
    $list=array();
    $i=0;
    while ($cresult=$stmt->fetch()){    


        $list[$i][0]=$cde;
        $list[$i][1]=$v_off;
        $list[$i][2]=$em_nm;
        $list[$i][3]=$q_id;
        $list[$i][4]=$v_m;
        $i=$i+1;
    }
    echo json_encode($list);        

This will be returned to ajax as result set and by using json parse in javascript part like this :

obj = JSON.parse(dataX);

$rows = json_decode($mysql_result,true);

as simple as that :-)


My simple fix to stop it putting speech marks around numeric values...

while($r = mysql_fetch_assoc($rs)){
    while($elm=each($r))
    {
        if(is_numeric($r[$elm["key"]])){
                    $r[$elm["key"]]=intval($r[$elm["key"]]);
        }
    }
    $rows[] = $r;
}   

The above will not work, in my experience, before you name the root-element in the array to something, I have not been able to access anything in the final json before that.

$sth = mysql_query("SELECT ...");
$rows = array();
while($r = mysql_fetch_assoc($sth)) {
    $rows['root_name'] = $r;
}
print json_encode($rows);

That should do the trick!


Sorry, this is extremely long after the question, but:

$sql = 'SELECT CONCAT("[", GROUP_CONCAT(CONCAT("{username:'",username,"'"), CONCAT(",email:'",email),"'}")), "]") 
AS json 
FROM users;'
$msl = mysql_query($sql)
print($msl["json"]);

Just basically:

"SELECT" Select the rows    
"CONCAT" Returns the string that results from concatenating (joining) all the arguments
"GROUP_CONCAT" Returns a string with concatenated non-NULL value from a group

The code below works fine here!

<?php

  $con=mysqli_connect("localhost",$username,$password,databaseName);

  // Check connection
  if (mysqli_connect_errno())
  {
   echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

  $query = "the query here";

  $result = mysqli_query($con,$query);

  $rows = array();
  while($r = mysqli_fetch_array($result)) {
    $rows[] = $r;
  }
  echo json_encode($rows);

  mysqli_close($con);
?>

<?php
define('HOST','localhost');
define('USER','root');
define('PASS','');
define('DB','dishant');

$con = mysqli_connect(HOST,USER,PASS,DB);


  if (mysqli_connect_errno())
  {
   echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

 $sql = "select * from demo ";

 $sth = mysqli_query($con,$sql);

$rows = array();

while($r = mysqli_fetch_array($sth,MYSQL_ASSOC)) {

 $row_array['id'] = $r;

    **array_push($rows,$row_array);**
}
echo json_encode($rows);

mysqli_close($con);
?>

aarray_push($rows,$row_array); help to build array otherwise it give last value in the while loop

this work like append method of StringBuilder in java


My simple fix to stop it putting speech marks around numeric values...

while($r = mysql_fetch_assoc($rs)){
    while($elm=each($r))
    {
        if(is_numeric($r[$elm["key"]])){
                    $r[$elm["key"]]=intval($r[$elm["key"]]);
        }
    }
    $rows[] = $r;
}   

One more option using FOR loop:

 $sth = mysql_query("SELECT ...");
 for($rows = array(); $row = mysql_fetch_assoc($sth); $rows[] = $row);
 print json_encode($rows);

The only disadvantage is that loop for is slower then e.g. while or especially foreach


http://www.php.net/mysql_query says "mysql_query() returns a resource".

http://www.php.net/json_encode says it can encode any value "except a resource".

You need to iterate through and collect the database results in an array, then json_encode the array.


The above will not work, in my experience, before you name the root-element in the array to something, I have not been able to access anything in the final json before that.

$sth = mysql_query("SELECT ...");
$rows = array();
while($r = mysql_fetch_assoc($sth)) {
    $rows['root_name'] = $r;
}
print json_encode($rows);

That should do the trick!


I solved like this

$stmt->bind_result($cde,$v_off,$em_nm,$q_id,$v_m);
    $list=array();
    $i=0;
    while ($cresult=$stmt->fetch()){    


        $list[$i][0]=$cde;
        $list[$i][1]=$v_off;
        $list[$i][2]=$em_nm;
        $list[$i][3]=$q_id;
        $list[$i][4]=$v_m;
        $i=$i+1;
    }
    echo json_encode($list);        

This will be returned to ajax as result set and by using json parse in javascript part like this :

obj = JSON.parse(dataX);

Code:

$rows = array();

while($r = mysqli_fetch_array($result,MYSQL_ASSOC)) {

 $row_array['result'] = $r;

  array_push($rows,$row_array); // here we push every iteration to an array otherwise you will get only last iteration value
}

echo json_encode($rows);

For example $result = mysql_query("SELECT * FROM userprofiles where NAME='TESTUSER' ");

1.) if $result is only one row.

$response = mysql_fetch_array($result);
echo json_encode($response);

2.) if $result is more than one row. You need to iterate the rows and save it to an array and return a json with array in it.

$rows = array();
if (mysql_num_rows($result) > 0) {
    while($r = mysql_fetch_assoc($result)) {
       $id = $r["USERID"];   //a column name (ex.ID) used to get a value of the single row at at time
       $rows[$id] = $r; //save the fetched row and add it to the array.
    }
}    
echo json_encode($rows);

One more option using FOR loop:

 $sth = mysql_query("SELECT ...");
 for($rows = array(); $row = mysql_fetch_assoc($sth); $rows[] = $row);
 print json_encode($rows);

The only disadvantage is that loop for is slower then e.g. while or especially foreach


Try this, this will create your object properly

 $result = mysql_query("SELECT ...");
 $rows = array();
   while($r = mysql_fetch_assoc($result)) {
     $rows['object_name'][] = $r;
   }

 print json_encode($rows);

$rows = json_decode($mysql_result,true);

as simple as that :-)


http://www.php.net/mysql_query says "mysql_query() returns a resource".

http://www.php.net/json_encode says it can encode any value "except a resource".

You need to iterate through and collect the database results in an array, then json_encode the array.


<?php
define('HOST','localhost');
define('USER','root');
define('PASS','');
define('DB','dishant');

$con = mysqli_connect(HOST,USER,PASS,DB);


  if (mysqli_connect_errno())
  {
   echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

 $sql = "select * from demo ";

 $sth = mysqli_query($con,$sql);

$rows = array();

while($r = mysqli_fetch_array($sth,MYSQL_ASSOC)) {

 $row_array['id'] = $r;

    **array_push($rows,$row_array);**
}
echo json_encode($rows);

mysqli_close($con);
?>

aarray_push($rows,$row_array); help to build array otherwise it give last value in the while loop

this work like append method of StringBuilder in java


we could simplify Paolo Bergantino answer like this

$sth = mysql_query("SELECT ...");
print json_encode(mysql_fetch_assoc($sth));

Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to mysql

Implement specialization in ER diagram How to post query parameters with Axios? PHP with MySQL 8.0+ error: The server requested authentication method unknown to the client Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver' phpMyAdmin - Error > Incorrect format parameter? Authentication plugin 'caching_sha2_password' is not supported How to resolve Unable to load authentication plugin 'caching_sha2_password' issue Connection Java-MySql : Public Key Retrieval is not allowed How to grant all privileges to root user in MySQL 8.0 MySQL 8.0 - Client does not support authentication protocol requested by server; consider upgrading MySQL client

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?