With the growing need for instant communication, real-time chat systems developed using PHP are becoming increasingly popular. One critical feature to enhance user experience is the ability to search chat history. This article explains how to build a search and display function for chat records in PHP-based chat systems.
The frontend provides a text input and a search button. JavaScript is used to capture input and send it to the server using Ajax, allowing seamless, asynchronous searching:
<input type="text" id="search-input">
<button onclick="search()">Search</button>
<script>
function search() {
var keyword = document.getElementById("search-input").value;
// Ajax request to fetch search results
// ...
}
</script>
On the server side, chat messages are stored in a database. A search endpoint accepts the keyword, performs a SQL query using the LIKE operator, and returns results in JSON format:
<?php
// Connect to the database
$pdo = new PDO('mysql:host=localhost;dbname=chat', 'root', 'password');
// Get the search keyword
$keyword = $_POST['keyword'];
// Perform SQL LIKE search
$stmt = $pdo->prepare("SELECT * FROM chat_records WHERE content LIKE ?");
$search_keyword = "%{$keyword}%";
$stmt->bindParam(1, $search_keyword);
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
// Return results as JSON
header('Content-Type: application/json');
echo json_encode($results);
Once the Ajax call receives results, JavaScript dynamically generates and displays the list of matching chat messages on the page:
<ul id="search-results"></ul>
<script>
function search() {
var keyword = document.getElementById("search-input").value;
$.post('/search.php', { keyword: keyword }, function(results) {
var list = "";
for (var i = 0; i < results.length; i++) {
list += "<li>" + results[i].content + "</li>";
}
document.getElementById("search-results").innerHTML = list;
});
}
</script>
The backend simply needs to process the query and return a clean JSON array. This interaction provides a seamless user experience and can be further extended for advanced search features:
<?php
// Connect to database
$pdo = new PDO('mysql:host=localhost;dbname=chat', 'root', 'password');
// Get keyword
$keyword = $_POST['keyword'];
// Query matching messages
$stmt = $pdo->prepare("SELECT * FROM chat_records WHERE content LIKE ?");
$search_keyword = "%{$keyword}%";
$stmt->bindParam(1, $search_keyword);
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
// Return as JSON
header('Content-Type: application/json');
echo json_encode($results);
This tutorial outlined the full process of implementing chat history search and display in a PHP chat system. By combining efficient SQL queries and dynamic front-end rendering, users can retrieve past messages quickly and intuitively. Developers can further expand on this feature with date filters, keyword highlighting, or pagination for better usability.