Converting MySQLi Results to JSON
In need of a lightweight data format for your mobile application? Converting your MySQLi query results to JSON is a breeze.
Steps to Convert MySQLi Results to JSON
Follow these steps to transform your MySQLi results into a JSON array:
Code Example
The following code demonstrates the conversion process:
$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);
Sample Output
The output will be a JSON array in the following format:
[ {"id":"31","name":"product_name1","price":"98"}, {"id":"30","name":"product_name2","price":"23"} ]
Alternatively, you can use mysqli_fetch_row instead of mysqli_fetch_assoc to obtain an array with numeric indexes:
while($row = $result->fetch_row()) { $myArray[] = $row; }
This will output an array in the following format:
[ ["31","product_name1","98"], ["30","product_name2","23"] ]
The above is the detailed content of How to Convert MySQLi Results into JSON for Mobile Apps?. For more information, please follow other related articles on the PHP Chinese website!