Home  >  Q&A  >  body text

How to convert mysqli query results to JSON format?

<p>I have a mysqli query that I need to format into JSON for a mobile application. </p> <p>I have successfully generated an XML document of the query results, but I'm looking for a more lightweight solution. (See current XML code below)</p> <pre class="brush:php;toolbar:false;">$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 nodes to 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 is ready echo $xml_string;</pre> <p><br /></p>
P粉794851975P粉794851975446 days ago484

reply all(2)I'll reply

  • P粉151466081

    P粉1514660812023-08-23 12:44:56

    This is how I create the 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();

    reply
    0
  • P粉044526217

    P粉0445262172023-08-23 09:42:01

    Just create an array from the query results and 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);

    The output results are as follows:

    [
        {"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 the following output:

    [
        ["31","product_name1","98"],
        ["30","product_name2","23"]
    ]

    reply
    0
  • Cancelreply