Home >Backend Development >PHP Tutorial >How to use PHP to implement search functionality

How to use PHP to implement search functionality

WBOY
WBOYOriginal
2024-05-02 12:54:02878browse

Implement the PHP search function through the following steps: Establish a database connection Define the search query (use the LIKE operator) Execute the query and obtain the results Display the search results (filtered by the search terms entered by the user)

如何使用 PHP 实现搜索功能

How to use PHP to implement the search function

The search function is an essential component in the website, which allows users to easily find the information they need. This tutorial will teach you how to build a simple search function using PHP.

1. Establish a database connection

First, establish a connection to the database:

$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "database";

$conn = new mysqli($servername, $username, $password, $dbname);

2. Define the search query

Store the search terms entered by the user In the variable ($search). Then, use the LIKE operator to build a SQL query to find records that contain the search term:

$search = $_GET["search"];
$sql = "SELECT * FROM table WHERE column LIKE '%$search%'";

3. Execute the query and get the results

Execute the SQL query and get the results:

$result = $conn->query($sql);
$data = array();
while ($row = $result->fetch_assoc()) {
  $data[] = $row;
}

4. Display search results

Display search results on the page:

echo "<ul>";
foreach ($data as $row) {
  echo "<li>" . $row["column"] . "</li>";
}
echo "</ul>";

Practical case

Consider a list of products with their names, descriptions and prices database. Users can enter a term into the search bar and the search results will show all products containing that term.

Code Snippet

// 搜索栏代码
<form action="search.php" method="GET">
  <input type="text" name="search">
  <input type="submit" value="Search">
</form>

// 搜索处理代码
$search = $_GET["search"];
$sql = "SELECT * FROM products WHERE name LIKE '%$search%'";
$result = $conn->query($sql);
$products = array();
while ($row = $result->fetch_assoc()) {
  $products[] = $row;
}

// 搜索结果显示代码
echo "<ul>";
foreach ($products as $product) {
  echo "<li>" . $product["name"] . " - $" . $product["price"] . "</li>";
}
echo "</ul>";

Implementing this search functionality will allow users to easily find specific products, thus enhancing the user experience of the website.

The above is the detailed content of How to use PHP to implement search functionality. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn