What are common pitfalls when outputting JSON objects from a MySQL database using PHP?

One common pitfall when outputting JSON objects from a MySQL database using PHP is not properly encoding special characters, which can lead to invalid JSON syntax. To solve this issue, you should use the `json_encode()` function in PHP to ensure that the data is correctly encoded.

// Fetch data from MySQL database
$query = "SELECT * FROM table";
$result = mysqli_query($connection, $query);

// Create an empty array to store the data
$data = array();

// Fetch rows from the result set
while ($row = mysqli_fetch_assoc($result)) {
    // Add each row to the data array
    $data[] = $row;
}

// Encode the data array into JSON format
$json = json_encode($data);

// Output the JSON data
header('Content-Type: application/json');
echo $json;