How can a timer be implemented in PHP to retrieve values from a SQL database and display them on a webpage?
To implement a timer in PHP to retrieve values from a SQL database and display them on a webpage, you can use the `setInterval` JavaScript function to periodically make an AJAX request to a PHP script that fetches data from the database. The PHP script should query the database and return the results in a JSON format. On the frontend, you can then update the webpage with the retrieved data.
<?php
// PHP script to fetch data from SQL database
// Connect to database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Fetch data from database
$sql = "SELECT * FROM table";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// Output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["name"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
Keywords
Related Questions
- Are there any specific functions or techniques in PHP that are commonly used for listing files in a folder?
- How can the error "Unknown column 'test' in 'where clause'" be avoided when executing a MySQL query in PHP?
- How can individual rows in a PHP-generated table be marked for deletion with a button?