Are there alternative methods to using PHP to fetch data from a MySQL database for JavaScript usage?

When fetching data from a MySQL database for JavaScript usage, one alternative method is to use AJAX to make a request to a PHP file that retrieves the data from the database. This allows for asynchronous communication between the client-side JavaScript and the server-side PHP script, enabling dynamic updates without needing to reload the entire page.

<?php
// PHP code to fetch data from a MySQL database

// Connect to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";
$conn = new mysqli($servername, $username, $password, $dbname);

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

// Query to fetch data from the database
$sql = "SELECT * FROM table_name";
$result = $conn->query($sql);

// Fetch data and encode it as JSON
$data = array();
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        $data[] = $row;
    }
}

echo json_encode($data);

// Close the connection
$conn->close();
?>