How can PHP be used to retrieve the last entry from a MySQL database table and pass it as a variable to JavaScript on a website?

To retrieve the last entry from a MySQL database table using PHP and pass it as a variable to JavaScript on a website, you can query the database for the last entry using an ORDER BY clause with DESC to get the latest entry. Once you have the data in PHP, you can encode it as JSON and echo it out to be accessed by JavaScript on the frontend.

<?php
// Connect to MySQL database
$connection = mysqli_connect("localhost", "username", "password", "database");

// Query to retrieve the last entry from the table
$query = "SELECT * FROM table_name ORDER BY id DESC LIMIT 1";
$result = mysqli_query($connection, $query);
$row = mysqli_fetch_assoc($result);

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

// Pass the JSON data to JavaScript
echo "<script> var lastEntry = $json_data; </script>";

// Close the database connection
mysqli_close($connection);
?>