Home > Article > Backend Development > How to use PHP database connection to implement search function
How to use PHP database connection to implement search function
In modern websites and applications, search function is a common and important function. It enables users to quickly find the information they want and provides a good user experience. This article will introduce how to use PHP database connection to implement search functionality.
Before starting to implement the search function, you first need to establish a database and create a table to store the data to be searched. Suppose we want to create a simple employee information table that includes the employee's name, position, and salary. The following is the SQL statement to create the table:
CREATE TABLE employees ( id INT PRIMARY KEY AUTO_INCREMENT, name VARCHAR(255), position VARCHAR(255), salary DECIMAL(10, 2) );
Next, we need an HTML form to receive the user's search query. Here is a simple search form:
<form action="search.php" method="GET"> <input type="text" name="query" placeholder="输入员工姓名"> <input type="submit" value="搜索"> </form>
After submitting the form, we need to write a PHP script to handle the search query and retrieve relevant data from the database. Here is an example of a simple search.php script:
<?php // 提取用户搜索查询 $query = $_GET['query']; // 建立数据库连接 $host = 'localhost'; $username = 'root'; $password = 'password'; $dbname = 'my_database'; $connection = new mysqli($host, $username, $password, $dbname); // 检查连接是否成功 if ($connection->connect_error) { die('数据库连接失败: ' . $connection->connect_error); } // 构建SQL查询语句 $sql = "SELECT * FROM employees WHERE name LIKE '%$query%'"; // 执行查询 $result = $connection->query($sql); // 检查查询结果 if ($result->num_rows > 0) { // 输出每一行数据 while ($row = $result->fetch_assoc()) { echo "姓名: " . $row['name'] . ", 职位: " . $row['position'] . ", 薪水: $" . $row['salary'] . "<br>"; } } else { echo "没有找到相关员工信息"; } // 关闭数据库连接 $connection->close(); ?>
In the above script, we first extract the user search query and store it in the variable $query. We then establish a database connection and execute the SQL query. The LIKE statement is used here to fuzzy match employee names. If there are matching records in the query results, we will output the data of each row, otherwise we will output "No relevant employee information found". Finally, we close the database connection.
The above is a simple example of how to use PHP database connection to implement the search function. According to actual needs, you can make appropriate modifications and extensions according to your own database table structure and search requirements. I hope this article will help you implement the search function!
The above is the detailed content of How to use PHP database connection to implement search function. For more information, please follow other related articles on the PHP Chinese website!