Current Location: Home> Latest Articles> PHP Beginner Tutorial: Easily Implement Website Search Function

PHP Beginner Tutorial: Easily Implement Website Search Function

M66 2025-10-17

How to Develop a Search Function Using PHP

In modern web development, a search function is an essential module that helps users quickly find the information they need. This article provides a simple example to demonstrate how to develop a basic search feature using PHP.

Preparation

Before implementing the search function, we need to prepare the following:

Database

Create a database table to store data. For example, create a table named student with fields student_id (student ID), name (student name), and age (student age).

Web Form

Create a web form to receive the user's search keyword, such as in the search.html file, including a text box and a submit button:

<form action="search.php" method="GET">
  <input type="text" name="keyword" placeholder="Enter search keyword">
  <input type="submit" value="Search">
</form>

PHP Script

Write a PHP script to handle user input and query the database, implemented in search.php:

<?php
// Connect to the database
$conn = mysqli_connect("localhost", "root", "password", "database");

// Check if the connection is successful
if (!$conn) {
  die("Database connection failed: " . mysqli_connect_error());
}

// Get the keyword input by the user
$keyword = $_GET['keyword'];

// Query the database for matching records
$query = "SELECT * FROM student WHERE name LIKE '%$keyword%'";
$result = mysqli_query($conn, $query);

// Process the query results and display
if (mysqli_num_rows($result) > 0) {
  while ($row = mysqli_fetch_assoc($result)) {
    echo "Student ID: " . $row['student_id'] . ", Name: " . $row['name'] . ", Age: " . $row['age'] . "<br>";
  }
} else {
  echo "No matching records found.";
}

// Close the database connection
mysqli_close($conn);
?>

Code Explanation

The code first connects to the database and checks if the connection is successful. Then it retrieves the keyword entered by the user and performs a fuzzy search in the database. The query results are displayed in a loop, and finally, the database connection is closed.

Summary

This article demonstrates how to implement a simple search feature using PHP, helping beginners understand the basic principle of search functionality. By matching user input with database records, search results are displayed. This is a basic example, and actual projects may require additional optimizations and security measures, such as preventing SQL injection and adding pagination.