As website content grows, offering users an efficient way to find information becomes increasingly important. A site search feature can greatly enhance both usability and the overall user experience. This tutorial walks you through implementing a basic search function using PHP.
Start by creating a front-end form that allows users to input their search terms:
<form method="GET" action="search.php">
<input type="text" name="keyword" placeholder="Enter keywords">
<input type="submit" value="Search">
</form>
This form uses the GET method to pass the user’s keyword to the results page (search.php) via the URL.
In search.php, the first step is to retrieve the submitted keyword:
<?php
$keyword = $_GET['keyword'];
// Connect to database and perform the query
// ...
?>
Here, the user input is accessed using $_GET. This keyword will be used to search relevant content from the database.
Use PDO to establish a connection and execute a query with basic keyword matching:
<?php
$keyword = $_GET['keyword'];
$host = 'localhost';
$dbname = 'database_name';
$username = 'username';
$password = 'password';
try {
$db = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
} catch (PDOException $e) {
die("Database connection failed: " . $e->getMessage());
}
$query = "SELECT * FROM articles WHERE title LIKE '%$keyword%' OR content LIKE '%$keyword%'";
$result = $db->query($query);
$articles = $result->fetchAll(PDO::FETCH_ASSOC);
?>
This query uses the LIKE operator to perform a fuzzy search in both the title and content fields of the articles table.
Loop through the results and output them in HTML:
<?php
foreach ($articles as $article) {
echo '<h3>' . $article['title'] . '</h3>';
echo '<p>' . $article['content'] . '</p>';
}
?>
This way, users can see all articles that contain the searched keyword in the title or content.
While this is a functional and simple example, real-world applications may require enhancements such as:
Optimizing your search functionality helps deliver a better user experience and can also improve engagement and conversions.
This tutorial covered the fundamental steps for building a basic site search feature using PHP, from form submission to database querying and rendering results. Although the example is simple, it provides a strong foundation for beginners. You can expand upon it based on your project needs with more advanced logic and tools.