Home > Article > Backend Development > How to Convert MySQLi Query Results to JSON?
To convert MySQLi query results to JSON format, follow these steps:
$mysqli = new mysqli('localhost','user','password','myDatabaseName'); $result = $mysqli->query("SELECT * FROM phase1");
$myArray = array(); while($row = $result->fetch_assoc()) { $myArray[] = $row; }
echo json_encode($myArray);
Output:
[ { "id": "31", "name": "product_name1", "price": "98" }, { "id": "30", "name": "product_name2", "price": "23" } ]
If you prefer an array with numbered keys, use fetch_row() instead of fetch_assoc().
while($row = $result->fetch_row()) { $myArray[] = $row; }
Output:
[ ["31","product_name1","98"], ["30","product_name2","23"] ]
This approach results in a lighter and more concise output compared to XML formatting, making it ideal for mobile applications.
The above is the detailed content of How to Convert MySQLi Query Results to JSON?. For more information, please follow other related articles on the PHP Chinese website!