Home  >  Article  >  Backend Development  >  How to Convert mysqli Results into JSON for Mobile Applications?

How to Convert mysqli Results into JSON for Mobile Applications?

Barbara Streisand
Barbara StreisandOriginal
2024-11-07 02:51:02764browse

How to Convert mysqli Results into JSON for Mobile Applications?

How to Swiftly Convert mysqli Results into JSON

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.

A Practical Solution

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn