Home > Backend Development > PHP Tutorial > How to Convert MySQLi Results into JSON for Mobile Apps?

How to Convert MySQLi Results into JSON for Mobile Apps?

Patricia Arquette
Release: 2024-11-07 17:53:03
Original
277 people have browsed it

How to Convert MySQLi Results into JSON for Mobile Apps?

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:

  1. Establish a MySQLi connection using mysqli_connect.
  2. Execute your query and store the result in a variable.
  3. Create an empty array to hold the results.
  4. Iterate through the query results using mysqli_fetch_assoc or mysqli_fetch_row to retrieve individual rows.
  5. Append each row to the array.
  6. Use json_encode to convert the array to JSON format.

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

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

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

This will output an array in the following format:

[
    ["31","product_name1","98"],
    ["30","product_name2","23"]
]
Copy after login

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!

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