How to convert mysqli result to JSON? [duplicate]

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"]
]

Leave a Comment