Home >Backend Development >PHP Tutorial >How to Convert mysqli Results into JSON for Mobile Applications?
Many developers find themselves needing to transform MySQL results into a portable JSON format, especially when building mobile applications. While generating an XML representation is possible, JSON offers a more lightweight alternative.
To achieve this conversion, start by creating an array from your mysqli query result. Subsequently, use the json_encode function to encode the array, which will produce a JSON string. Here's a code sample for your reference:
$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);
This code generates JSON output resembling the following:
[ {"id":"31","name":"product_name1","price":"98"}, {"id":"30","name":"product_name2","price":"23"} ]
Alternatively, you can use fetch_row() instead of fetch_assoc() to obtain an output in this format:
[ ["31","product_name1","98"], ["30","product_name2","23"] ]
With this simple adjustment, you can now integrate your MySQL data seamlessly into your mobile applications, harnessing the flexibility of JSON.
The above is the detailed content of How to Convert mysqli Results into JSON for Mobile Applications?. For more information, please follow other related articles on the PHP Chinese website!