Home » Php » php – How to convert mysqli result to JSON?

php – How to convert mysqli result to JSON?

Posted by: admin April 23, 2020 Leave a comment

Questions:

I have a mysqli query which I need to format as JSON for a mobile application.

I have managed to produce an XML document for the query results, however I am looking for something more lightweight. (See below for my current XML code)

$mysql = new mysqli(DB_SERVER,DB_USER,DB_PASSWORD,DB_NAME) or die('There was a problem connecting to the database');

$stmt = $mysql->prepare('SELECT DISTINCT title FROM sections ORDER BY title ASC');
$stmt->execute();
$stmt->bind_result($title);

// create xml format
$doc = new DomDocument('1.0');

// create root node
$root = $doc->createElement('xml');
$root = $doc->appendChild($root);

// add node for each row
while($row = $stmt->fetch()) : 

    $occ = $doc->createElement('data');  
    $occ = $root->appendChild($occ);  

    $child = $doc->createElement('section');  
    $child = $occ->appendChild($child);  
    $value = $doc->createTextNode($title);  
    $value = $child->appendChild($value);  

endwhile;

$xml_string = $doc->saveXML();  

header('Content-Type: application/xml; charset=ISO-8859-1');

// output xml jQuery ready

echo $xml_string;
How to&Answers:
$mysqli = new mysqli('localhost','user','password','myDatabaseName');
$myArray = array();
if ($result = $mysqli->query("SELECT * FROM phase1")) {

    while($row = $result->fetch_array(MYSQLI_ASSOC)) {
            $myArray[] = $row;
    }
    echo json_encode($myArray);
}

$result->close();
$mysqli->close();
  1. $row = $result->fetch_array(MYSQLI_ASSOC)
  2. $myArray[] = $row

output like this:

[
    {"id":"31","name":"pruduct_name1","price":"98"},
    {"id":"30","name":"pruduct_name2","price":"23"}
]

If you want another style, you can try this:

  1. $row = $result->fetch_row()
  2. $myArray[] = $row

output will like this:

[
    ["31","pruduct_name1","98"],
    ["30","pruduct_name2","23"]
]

Answer:

Here’s how I made my JSON feed:

$mysqli = new mysqli('localhost', 'user', 'password', 'myDatabaseName');
$myArray = array();
if ($result = $mysqli->query("SELECT * FROM phase1")) {
    $tempArray = array();
    while ($row = $result->fetch_object()) {
        $tempArray = $row;
        array_push($myArray, $tempArray);
    }
    echo json_encode($myArray);
}

$result->close();
$mysqli->close();

Answer:

As mentioned, json_encode will help you. The easiest way is to fetch your results as you already do it and build up an array that can be passed to json_encode.

Example:

$json = array();
while($row = $stmt->fetch()){
  $json[]['foo'] = "your content  here";
  $json[]['bar'] = "more database results";
}
echo json_encode($json);

Your $json will be a regular array with each element in it’s own index.

There should be very little changed in your above code, alternativly, you can return both XML and JSON since most of the code is the same.

Answer:

I managed to run this code:

<?php
//create an array
$emparray = array();
while ($row = mysqli_fetch_assoc($result)) {
    $emparray[] = $row;
}
return json_encode($emparray);

Answer:

There is one essential thing about JSON – the data must be UTF-8 encoded. Therefore, the proper encoding must be set for the database connection.

The rest is as silly as any other database operation

$mysql = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME);
$mysql->set_charset('utf8mb4');

$sql = 'SELECT DISTINCT title FROM sections ORDER BY title ASC';
$data = $mysql->query($sql)->fetch_all(MYSQLI_ASSOC);
echo json_encode($data);

Answer:

If you have mysqlnd extension installed + enabled in php, you can use:

$mysqli = new mysqli('localhost','user','password','myDatabaseName');

$result = $mysqli->query("SELECT * FROM phase1");

//Copy result into a associative array
$resultArray = $result->fetch_all(MYSQLI_ASSOC);

echo json_encode($resultArray);

mysqli::fetch_all() needs mysqlnd driver to be installed before you
can use it.