Home >Backend Development >PHP Tutorial >How to use PHP to implement efficient database search function
How to use PHP to achieve efficient database search function
In modern website development, the database plays a vital role. In the database, the search function is one of the frequently used functions. This article will introduce how to use the PHP programming language to implement efficient database search functions and provide specific code examples.
1. Preparation work
Before we start writing code, we need to prepare the following work:
2. Write code
First, we need to write an HTML form to receive the search content entered by the user. The code example is as follows:
<form action="search.php" method="post"> <input type="text" name="keyword" placeholder="请输入搜索关键字"> <input type="submit" value="搜索"> </form>
Next, we need to write the search.php file, which will receive the user's search keywords and search for matching data in the database. The code example is as follows:
<?php // 连接数据库 $servername = "localhost"; $username = "root"; $password = "password"; $dbname = "mydatabase"; $conn = new mysqli($servername, $username, $password, $dbname); if ($conn->connect_error) { die("连接失败: " . $conn->connect_error); } // 获取用户输入的搜索关键字 $keyword = $_POST['keyword']; // 构建SQL查询语句 $sql = "SELECT * FROM mytable WHERE column_name LIKE '%$keyword%'"; $result = $conn->query($sql); // 输出搜索结果 if ($result->num_rows > 0) { while($row = $result->fetch_assoc()) { echo "ID: " . $row["id"]. " - Name: " . $row["name"]. "<br>"; } } else { echo "没有找到匹配的结果"; } // 关闭数据库连接 $conn->close(); ?>
In the above code, we first connect to the database through the constructor of the mysqli class. Then, get the search keyword entered by the user through $_POST['keyword']. Next, we constructed a SQL query using the LIKE operator for fuzzy matching. In the query results, we output each matching piece of data by looping through it.
3. Code operation and optimization
Save the above code as a search.php file and place it in the appropriate location. Make sure that the action attribute in the HTML form is consistent with the search.php file. The paths are consistent.
Open the page containing the search form in the browser, enter the keyword and click the search button, the program will output the search results to the page.
However, the above code is just an example of a basic search function, and there may still be some problems that require further optimization. Here are some suggestions for further optimization:
In summary, this article introduces how to use PHP to implement efficient database search functions and provides corresponding code examples. I hope it will be helpful to readers and inspire more innovative ideas.
The above is the detailed content of How to use PHP to implement efficient database search function. For more information, please follow other related articles on the PHP Chinese website!