Home > Article > Backend Development > PHP form processing: form data filtering and search
PHP Form Processing: Form Data Filtering and Search
Introduction:
In Web development, forms are one of the most important components. Forms allow users to easily enter and submit data. However, sometimes we need to filter and search form data to better meet user needs. This article will introduce how to use PHP to process the filtering and search functions of form data, and provide code examples.
1. Form data filtering
HTML code:
<form action="filter.php" method="post"> <label for="name">姓名:</label> <input type="text" name="name" id="name"> <label for="age">年龄:</label> <input type="number" name="age" id="age"> <label for="gender">性别:</label> <select name="gender" id="gender"> <option value="">不限</option> <option value="male">男</option> <option value="female">女</option> </select> <input type="submit" value="筛选"> </form>
PHP code (filter.php):
<?php // 获取表单提交的数据 $name = $_POST['name']; $age = $_POST['age']; $gender = $_POST['gender']; // 构建查询条件 $where = []; if (!empty($name)) { $where[] = "name LIKE '%$name%'"; } if (!empty($age)) { $where[] = "age = $age"; } if (!empty($gender)) { $where[] = "gender = '$gender'"; } // 拼接查询语句 $query = "SELECT * FROM users"; if (!empty($where)) { $query .= " WHERE " . implode(' AND ', $where); } // 执行查询操作并输出结果 // ... ?>
In the above example code, the filter conditions entered by the user are submitted through the HTML form, and then Construct query statements based on conditions in PHP code and perform query operations. Finally, perform corresponding processing according to the query results.
2. Form data search
HTML code:
<form action="search.php" method="get"> <label for="keyword">关键词:</label> <input type="text" name="keyword" id="keyword"> <input type="submit" value="搜索"> </form>
PHP code (search.php):
<?php // 获取搜索关键词 $keyword = $_GET['keyword']; // 拼接查询语句 $query = "SELECT * FROM users"; if (!empty($keyword)) { $query .= " WHERE name LIKE '%$keyword%'"; } // 执行查询操作并输出结果 // ... ?>
In the above example code, we submit the keywords entered by the user through the HTML form. Then build the query statement in the PHP code and execute the query operation. Finally, perform corresponding processing according to the query results.
Conclusion:
Through the above sample code, we can see how to use PHP to process the filtering and search functions of form data. By flexibly using form processing technology, we can better meet user needs and improve website experience. Hope this article helps you!
The above is the detailed content of PHP form processing: form data filtering and search. For more information, please follow other related articles on the PHP Chinese website!