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

How to Convert MySQLi Query Results to JSON?

Linda Hamilton
Linda HamiltonOriginal
2024-11-11 04:52:03868browse

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");
  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;
}
  1. Encode the array as JSON using the json_encode() function.
echo json_encode($myArray);

Output:

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

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

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

Output:

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

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!

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