Convert MySQLi Result to JSON: A Practical Approach
When integrating with mobile applications, converting MySQLi results into JSON format becomes crucial. This article delves into a straightforward solution to accomplish this conversion efficiently.
The Conversion Technique
Rather than utilizing complex XML structures, JSON offers a lightweight and convenient alternative for data interchange. To convert MySQLi results to JSON, follow these steps:
Example Implementation
Consider the following PHP code:
$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 establishes a database connection, executes a query, converts the results into an array, and finally encodes it into JSON format.
Output Variation
Depending on the desired output style, you can modify the fetch method accordingly.
Associative array:
$result->fetch_assoc()
Output:
[ { "id": "31", "name": "product_name1", "price": "98" }, { "id": "30", "name": "product_name2", "price": "23" } ]
Indexed array:
$result->fetch_row()
Output:
[ ["31", "product_name1", "98"], ["30", "product_name2", "23"] ]
Conclusion
By adopting this straightforward approach, you can seamlessly convert MySQLi query results into JSON format, enabling efficient data transfer and integration with mobile applications.
The above is the detailed content of How to Convert MySQLi Results to JSON for Mobile App Integration?. For more information, please follow other related articles on the PHP Chinese website!