How can PHP be used to efficiently process and output data from a MySQL database in JSON format?
To efficiently process and output data from a MySQL database in JSON format using PHP, you can use the following steps: 1. Connect to the MySQL database using mysqli or PDO. 2. Fetch the data from the database using a query. 3. Convert the fetched data into a JSON format using json_encode() function. 4. Output the JSON data to the client.
<?php
// Connect to MySQL database
$mysqli = new mysqli("localhost", "username", "password", "database");
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
// Fetch data from the database
$result = $mysqli->query("SELECT * FROM table");
$data = $result->fetch_all(MYSQLI_ASSOC);
// Convert data to JSON format
$json_data = json_encode($data);
// Output JSON data
header('Content-Type: application/json');
echo $json_data;
// Close connection
$mysqli->close();
?>