What is the recommended method to fetch data from a MySQL database and convert it into JSON format in PHP?

To fetch data from a MySQL database and convert it into JSON format in PHP, you can use the mysqli extension to connect to the database, fetch the data using a query, and then encode the result into JSON format using the json_encode() function.

<?php
// Connect to MySQL database
$mysqli = new mysqli("localhost", "username", "password", "database_name");

// Check connection
if ($mysqli->connect_error) {
    die("Connection failed: " . $mysqli->connect_error);
}

// Fetch data from database
$result = $mysqli->query("SELECT * FROM table_name");

// Convert data to JSON format
$data = array();
while ($row = $result->fetch_assoc()) {
    $data[] = $row;
}

echo json_encode($data);

// Close connection
$mysqli->close();
?>