How can PHP be used to continuously retrieve and display new messages from a MySQL database for a chat frame?
To continuously retrieve and display new messages from a MySQL database for a chat frame, you can use AJAX in combination with PHP. AJAX can be used to periodically send requests to a PHP script that fetches new messages from the database and returns them as JSON data. The PHP script can then be used to query the database for new messages and return them to the client-side code for display.
<?php
// Connect to MySQL database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "chat_db";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Fetch new messages from database
$sql = "SELECT * FROM messages WHERE timestamp > :lastTimestamp";
$stmt = $conn->prepare($sql);
$stmt->bind_param(":lastTimestamp", $_GET['lastTimestamp']);
$stmt->execute();
$result = $stmt->get_result();
$messages = [];
while ($row = $result->fetch_assoc()) {
$messages[] = $row;
}
// Return new messages as JSON data
header('Content-Type: application/json');
echo json_encode($messages);
$conn->close();
?>