What are some potential solutions for retrieving and processing data from PHP to JavaScript without directly accessing the database?

One potential solution for retrieving and processing data from PHP to JavaScript without directly accessing the database is to use AJAX to make a request to a PHP file that fetches the data from the database and returns it in a JSON format. This way, the JavaScript code can then parse the JSON data and use it as needed without exposing direct database access.

<?php
// PHP file to fetch data from the database and return it in JSON format

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

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

// Return data in JSON format
header('Content-Type: application/json');
echo json_encode($data);
?>