What is the common issue when trying to generate a JSON string from a MySQL query in PHP?
When trying to generate a JSON string from a MySQL query in PHP, a common issue is that the JSON output may not be formatted correctly due to special characters or encoding problems. To solve this issue, you can use the `json_encode()` function in PHP to properly encode the query result into a JSON string.
// Connect to MySQL database
$connection = mysqli_connect("localhost", "username", "password", "database");
// Perform MySQL query
$query = "SELECT * FROM table";
$result = mysqli_query($connection, $query);
// Fetch query result and encode into JSON
$data = array();
while ($row = mysqli_fetch_assoc($result)) {
$data[] = $row;
}
$json_string = json_encode($data, JSON_UNESCAPED_UNICODE);
echo $json_string;
// Close database connection
mysqli_close($connection);
Keywords
Related Questions
- In PHP, what steps can be taken to improve code readability and maintainability, especially in the context of user authentication scripts?
- What are the differences between using cURL and file_get_contents in PHP to retrieve and save a file from a URL?
- Are there any PHP viewers available that allow for the execution of PHP scripts independently of a web server?