Home >Backend Development >PHP Tutorial >PHP form processing: form data query and filtering
PHP form processing: form data query and filtering
The following is an example of a simple query and filter form:
<form action="process.php" method="POST"> <label for="name">姓名:</label> <input type="text" id="name" name="name"> <label for="gender">性别:</label> <select id="gender" name="gender"> <option value="Male">男</option> <option value="Female">女</option> </select> <label for="age">年龄:</label> <input type="number" id="age" name="age"> <input type="submit" value="查询"> </form>
$name = $_POST['name']; $gender = $_POST['gender']; $age = $_POST['age'];
Next, we can use this data to query related information in the database. Suppose we have a student table that contains fields such as name, gender, age, etc. The following is a simple database query example:
// 连接数据库 $conn = mysqli_connect('localhost', 'username', 'password', 'database'); // 查询语句 $sql = "SELECT * FROM students WHERE 1=1"; // 添加查询条件 if (!empty($name)) { $sql .= " AND name LIKE '%$name%'"; } if (!empty($gender)) { $sql .= " AND gender='$gender'"; } if (!empty($age)) { $sql .= " AND age=$age"; } // 执行查询 $result = mysqli_query($conn, $sql); // 处理查询结果 if (mysqli_num_rows($result) > 0) { while ($row = mysqli_fetch_assoc($result)) { // 处理每一行数据 } } else { echo "没有找到相关记录"; } // 关闭数据库连接 mysqli_close($conn);
In the above example, we implement dynamic query by splicing SQL statements. First, we define an initial SELECT statement, and then dynamically add a WHERE clause based on the query conditions submitted by the form.
Finally, we use the mysqli_query function to execute the query, and use the mysqli_num_rows function to get the number of rows in the query result. If there are query results, you can use the mysqli_fetch_assoc function to process the data row by row.
if (mysqli_num_rows($result) > 0) { echo "<table>"; echo "<tr><th>姓名</th><th>性别</th><th>年龄</th></tr>"; while ($row = mysqli_fetch_assoc($result)) { echo "<tr>"; echo "<td>".$row['name']."</td>"; echo "<td>".$row['gender']."</td>"; echo "<td>".$row['age']."</td>"; echo "</tr>"; } echo "</table>"; } else { echo "没有找到相关记录"; }
In the above code, we loop through each record of the query results and output it in the form of a table.
In fact, form processing and data query are common functions in web development, and this article only provides a simple example. In actual development, more code and technology may be required depending on the complexity of specific requirements. However, by mastering the basic processing procedures and related technologies, a good foundation can be provided for subsequent development.
The above is the detailed content of PHP form processing: form data query and filtering. For more information, please follow other related articles on the PHP Chinese website!