With the widespread use of social networks and diverse online communication methods, real-time chat systems have become essential tools for daily life and work. As chat histories grow over time, quickly and accurately retrieving past messages becomes critical for user experience.
This article explains how to implement chat history search and display search results in a PHP-based real-time chat system, providing practical code examples for developers to reference.
Before implementing search functionality, a well-structured database is essential. A typical chat records table contains the following fields:
First, add a search box and button on the user interface, allowing users to input keywords and submit search requests.
<form action="search.php" method="post">
<input type="text" name="keyword" placeholder="Enter keyword">
<input type="submit" value="Search">
</form>
The backend PHP script processes the search request by connecting to the database and performing a fuzzy query, as shown below:
<?php
// Database connection settings
$host = 'localhost';
$dbname = 'chat_system';
$username = 'root';
$password = '';
try {
$conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo "Database connection failed: " . $e->getMessage();
exit;
}
$keyword = $_POST['keyword'];
$sql = "SELECT * FROM chat_records WHERE message LIKE :keyword";
$query = $conn->prepare($sql);
$query->bindValue(':keyword', '%' . $keyword . '%');
$query->execute();
$results = $query->fetchAll(PDO::FETCH_ASSOC);
foreach ($results as $result) {
echo $result['sender'] . ' ' . $result['message'] . '<br>';
}
?>
After submitting a search, the user is redirected to the results page where relevant chat messages are displayed. Example display code is as follows:
<?php if(count($results) > 0): ?>
<?php foreach($results as $result): ?>
<div class="search-result">
<p><?php echo $result['sender']; ?>: <?php echo $result['message']; ?></p>
<p><?php echo $result['timestamp']; ?></p>
</div>
<?php endforeach; ?>
<?php else: ?>
<p>No related chat records found.</p>
<?php endif; ?>
The logic is straightforward: check if there are any results; if yes, display sender, message, and timestamp for each record; otherwise, show a message indicating no matches were found.
By combining a suitable database design with PHP backend processing and a user-friendly front-end search interface, chat history search and result display can be effectively realized in a real-time chat system. This basic implementation can be further enhanced with features like pagination, search optimization, and access control to improve usability and performance.