How can PHP be integrated with JavaScript to achieve real-time updates on a webpage without refreshing the entire page?
To achieve real-time updates on a webpage without refreshing the entire page, you can use AJAX (Asynchronous JavaScript and XML) to send requests to a PHP script that fetches or updates data from a database. The PHP script will return the data in JSON format, which can be processed by JavaScript to update specific parts of the webpage dynamically.
// PHP script to fetch data from a database and return it in JSON format
<?php
// Connect to database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
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();
?>