How to use PHP to develop a simple search function
With the development of the Internet, the search function has become an inseparable part of everyone's daily life. In website development, search function is an indispensable and important component. This article will introduce how to use PHP to develop a simple search function to help beginners understand the basic search implementation principles.
Preparation
Before we start, we need to prepare the following three basic parts:
<form action="search.php" method="GET"> <input type="text" name="keyword" placeholder="请输入搜索关键字"> <input type="submit" value="搜索"> </form>
Implementing search function
The following is a sample code for a simple PHP search function:
<?php // 连接数据库 $conn = mysqli_connect("localhost", "root", "password", "database"); // 检查连接是否成功 if (!$conn) { die("数据库连接失败: " . mysqli_connect_error()); } // 获取用户输入的关键字 $keyword = $_GET['keyword']; // 查询数据库中匹配关键字的记录 $query = "SELECT * FROM student WHERE name LIKE '%$keyword%'"; $result = mysqli_query($conn, $query); // 处理查询结果并显示在网页上 if (mysqli_num_rows($result) > 0) { while ($row = mysqli_fetch_assoc($result)) { echo "学号:" . $row['student_id'] . ",姓名:" . $row['name'] . ",年龄:" . $row['age'] . "<br>"; } } else { echo "没有找到匹配的记录。"; } // 关闭数据库连接 mysqli_close($conn); ?>
Parsing code
The above code first connects to the database and checks whether the connection is success. Next, obtain the keywords entered by the user in the form, and conduct a fuzzy matching query in the database based on the keywords. The query results are obtained through loop traversal to obtain each record, and the results are displayed on the web page. Finally, close the database connection.
Summary
The above are the basic steps and sample code for developing a simple search function using PHP. Through this example, we can understand the basic principle of implementing a simple search, that is, matching the keywords entered by the user with the records in the database. Of course, this is just a simple example, and there are more complex requirements and processing in actual applications. I hope this article will be helpful to beginners, and everyone is welcome to further learn and explore.
The above is the detailed content of How to develop a simple search function using PHP. For more information, please follow other related articles on the PHP Chinese website!