Home > Backend Development > PHP Tutorial > How to Convert MySQLi Query Results to JSON?

How to Convert MySQLi Query Results to JSON?

Linda Hamilton
Release: 2024-11-11 04:52:03
Original
918 people have browsed it

How to Convert MySQLi Query Results to JSON?

How to Convert MySQLi Result to JSON

To convert MySQLi query results to JSON format, follow these steps:

  1. Execute the MySQLi query and store the results in a variable.
$mysqli = new mysqli('localhost','user','password','myDatabaseName');
$result = $mysqli->query("SELECT * FROM phase1");
Copy after login
  1. Create an array from the query result using the fetch_assoc() method. This method returns an associative array where the keys are the column names and the values are the corresponding values.
$myArray = array();
while($row = $result->fetch_assoc()) {
    $myArray[] = $row;
}
Copy after login
  1. Encode the array as JSON using the json_encode() function.
echo json_encode($myArray);
Copy after login

Output:

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

If you prefer an array with numbered keys, use fetch_row() instead of fetch_assoc().

while($row = $result->fetch_row()) {
    $myArray[] = $row;
}
Copy after login

Output:

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

This approach results in a lighter and more concise output compared to XML formatting, making it ideal for mobile applications.

The above is the detailed content of How to Convert MySQLi Query Results to JSON?. 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