What is the recommended approach for continuously querying a database and updating values on a webpage without reloading using PHP?
To continuously query a database and update values on a webpage without reloading, you can use AJAX in combination with PHP. AJAX allows you to make asynchronous requests to the server, retrieve data, and update the webpage dynamically. You can create a PHP script that fetches data from the database and returns it in JSON format, then use JavaScript to update the webpage with the retrieved data.
<?php
// PHP script to fetch data from database and return it in JSON format
// 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);
$data = array();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$data[] = $row;
}
}
// Return data in JSON format
header('Content-Type: application/json');
echo json_encode($data);
$conn->close();
?>
Related questions
-
Smarty template engine PHP
-
PHP resources online
-
PHP VB.NET data validation