Home >Backend Development >PHP Problem >How to implement search query function in php
With the development of the Internet, online searches have become more and more common. Whether it is an e-commerce website or a blogging website, search functionality is crucial. In PHP, it is not difficult to implement a search query function. This article will introduce how to use PHP to write a search query function.
Before using PHP to implement search queries, you must first set up the database. First you need to create a database and add data tables to it. The data table should contain the data fields to be searched, such as article title, content, author, etc.
Create a search query form in HTML as shown below:
<form action="search.php" method="get"> <input type="text" name="search"> <button type="submit">搜索</button> </form>
This code contains a text box and a Submit button, users can enter the keywords to search and submit the form.
Now we need to write a PHP script to process the search keywords entered by the user and obtain matching results from the database. The following is a simple search query script:
<?php // 连接数据库 $dbhost = 'localhost'; $dbuser = 'root'; $dbpass = ''; $dbname = 'myDB'; $conn = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname); // 处理用户输入的搜索关键字 $search = mysqli_real_escape_string($conn, $_GET['search']); // 从数据库中获取匹配的结果 $sql = "SELECT * FROM articles WHERE title LIKE '%$search%' OR content LIKE '%$search%'"; $result = mysqli_query($conn, $sql); // 输出结果 while ($row = mysqli_fetch_assoc($result)) { echo $row['title'] . '<br>'; echo $row['content'] . '<br>'; echo $row['author'] . '<br>'; } // 关闭连接 mysqli_close($conn); ?>
This script connects to the database and gets matching results from the database based on the search keywords entered by the user. Note that the mysqli_real_escape_string() function is used to process the search keywords entered by the user to prevent SQL injection attacks.
The above script implements the basic search query function, but it can be further optimized. The following are some optimization suggestions:
Conclusion
It is not difficult to implement search query function using PHP. It only requires some basic database knowledge and programming skills. Incorporating the suggestions in this article into your code can improve the efficiency and user experience of your search query functionality.
The above is the detailed content of How to implement search query function in php. For more information, please follow other related articles on the PHP Chinese website!