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
Patricia ArquetteOriginal
2024-11-07 17:53:03322browse

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);

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"}
]

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;
}

This will output an array in the following format:

[
    ["31","product_name1","98"],
    ["30","product_name2","23"]
]

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!

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