What are the best practices for handling data retrieval from a database in PHP for use in JavaScript?

When retrieving data from a database in PHP for use in JavaScript, it is best practice to encode the data in JSON format to ensure compatibility between the two languages. This can be achieved by fetching the data from the database using PHP, encoding it as JSON, and then echoing it back to the client-side JavaScript for processing.

// Connect to the database
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');

// Fetch data from the database
$stmt = $pdo->query('SELECT * FROM mytable');
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Encode the data as JSON
$jsonData = json_encode($data);

// Echo the JSON data back to the client-side JavaScript
echo $jsonData;