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

How to Convert mysqli Results into JSON for Mobile Applications?

Barbara Streisand
Release: 2024-11-07 02:51:02
Original
848 people have browsed it

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);
Copy after login

This code generates JSON output resembling the following:

[
    {"id":"31","name":"product_name1","price":"98"},
    {"id":"30","name":"product_name2","price":"23"}
]
Copy after login

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"]
]
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template