How to use PHP to handle data search and filtering in forms
Summary:
When users submit data through forms, we need to search and filter the data Filter to get the desired results. In PHP, we can use some techniques to achieve these functions. This article will introduce how to use PHP to handle data search and filtering in forms, and provide corresponding code examples.
Introduction:
Forms are usually used to collect user input data, which can be text, numbers, dates, etc. Once the user submits the form, we need to process this data in order to get the results we want. Especially in the search function, we need to filter and retrieve the corresponding data based on the user's input.
The following is a simple code example:
<?php //获取用户输入的关键字 $keyword = $_POST['keyword']; //连接数据库 $conn = new mysqli("localhost", "root", "password", "database"); //处理搜索 $sql = "SELECT * FROM table WHERE column 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 "0 结果"; } //关闭数据库连接 $conn->close(); ?>
In this example, we get the keyword entered by the user through $_POST['keyword']. We then use the LIKE statement to search the column for results containing the keyword. Finally, we display the matching results through a loop and the fetch_assoc() method.
The following is a simple code example:
<?php //获取用户输入的数据 $name = $_POST['name']; $email = $_POST['email']; //过滤数据 $name = filter_var($name, FILTER_SANITIZE_STRING); $email = filter_var($email, FILTER_VALIDATE_EMAIL); //显示过滤后的结果 echo "Name: " . $name . "<br>"; echo "Email: " . $email . "<br>"; ?>
In this example, we use the filter_var() function to filter the $name and $email variables entered by the user. FILTER_SANITIZE_STRING filter is used to remove HTML tags and special characters in strings. The FILTER_VALIDATE_EMAIL filter is used to verify the validity of email addresses.
Conclusion:
Searching and filtering are very common needs when processing form data. Using PHP, we can accomplish these tasks easily. This article explains how to use PHP to handle data searching and filtering in forms, and provides corresponding code examples. Hopefully these examples will help readers better understand and apply these techniques.
The above is the detailed content of How to handle data searching and filtering in forms using PHP. For more information, please follow other related articles on the PHP Chinese website!