How to Convert MySQLi Results to JSON for Mobile App Integration?

Linda Hamilton
Release: 2024-11-08 11:11:02
Original
975 people have browsed it

How to Convert MySQLi Results to JSON for Mobile App Integration?

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:

  1. Execute the desired query using MySQLi.
  2. Fetch the results into an array using the fetch_assoc() or fetch_row() method.
  3. Encode the array into JSON format using json_encode().

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

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

    Output:

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

    $result->fetch_row()
    Copy after login

    Output:

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

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!

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