What is the best practice for retrieving data from a MySQL database, storing it in an array, and outputting it as JSON in PHP?
When retrieving data from a MySQL database in PHP and outputting it as JSON, it is best practice to fetch the data using a prepared statement to prevent SQL injection attacks. Once the data is fetched, store it in an array and then encode the array as JSON using the json_encode() function before outputting it.
<?php
// Establish a connection to the MySQL database
$pdo = new PDO('mysql:host=localhost;dbname=database_name', 'username', 'password');
// Prepare a SQL query to retrieve data
$stmt = $pdo->prepare("SELECT * FROM table_name");
$stmt->execute();
// Fetch the data and store it in an array
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
// Encode the array as JSON and output it
echo json_encode($data);
?>