Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert mysqli result to JSON? [duplicate]

Tags:

json

php

mysqli

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;
like image 201
ab24 Avatar asked Jul 28 '10 10:07

ab24


2 Answers

Simply create an array from the query result and then encode it

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

output like this:

[
    {"id":"31","name":"product_name1","price":"98"},
    {"id":"30","name":"product_name2","price":"23"}
]

If you want another style, you can change fetch_assoc() to fetch_row() and get output like this:

[
    ["31","product_name1","98"],
    ["30","product_name2","23"]
]
like image 67
Will Avatar answered Nov 14 '22 09:11

Will


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();
like image 16
Keith Brown Avatar answered Nov 14 '22 09:11

Keith Brown