In web development, search functionality plays a key role in improving user experience. A well-designed search system allows users to find the information they need quickly. This article demonstrates how to build a simple yet effective search feature using PHP, perfect for lightweight applications.
We start by creating an array to simulate the data set. In real-world applications, this data typically comes from a database or external source.
$data = array(
array("id" => 1, "name" => "Zhang San", "age" => 25, "city" => "Beijing"),
array("id" => 2, "name" => "Li Si", "age" => 30, "city" => "Shanghai"),
array("id" => 3, "name" => "Wang Wu", "age" => 35, "city" => "Guangzhou"),
// More data...
);
Users enter search keywords via a form, which sends the input to the PHP backend. Below is a basic HTML search form:
<form action="search.php" method="get">
<input type="text" name="keyword" placeholder="Enter keyword..." />
<input type="submit" value="Search" />
</form>
In the search.php file, retrieve the keyword and filter the dataset to find matching entries. The search checks the name, age, and city fields:
$keyword = $_GET['keyword'];
if ($keyword === "") {
echo json_encode($data);
exit;
}
$results = array();
foreach ($data as $item) {
if (strpos($item['name'], $keyword) !== false ||
strpos((string)$item['age'], $keyword) !== false ||
strpos($item['city'], $keyword) !== false) {
$results[] = $item;
}
}
echo json_encode($results);
You can use AJAX to send a request to search.php and display results on the page without reloading. Here's how it can be done with JavaScript:
var keyword = document.getElementById("keyword").value;
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
var results = JSON.parse(xhr.responseText);
var resultContainer = document.getElementById("result-container");
resultContainer.innerHTML = "";
for (var i = 0; i < results.length; i++) {
var item = document.createElement("div");
item.innerHTML = results[i].name + ", " + results[i].age + ", " + results[i].city;
resultContainer.appendChild(item);
}
}
};
xhr.open("GET", "search.php?keyword=" + keyword, true);
xhr.send();
With this example, we've built a simple search system using PHP and plain JavaScript. It includes a form input, keyword filtering, and dynamic result display. This solution is suitable for small to medium projects and can be extended to include more advanced features such as fuzzy search, pagination, or database integration.