Search feature with multiple criteria - PHP/MySQL
How can i create a search page with multiple criteria where at least a criteria should be checked.
Table Structure
- ID [开发者_开发百科pk]
- Name
- Sex
- Location
I want to create a search form where user will be able to search by name or by name,sex or by name,sex,location or any such combination among [name,sex,location]
How to design the query ?
Edit
You can check to see if the post for a particular field is empty, if it's not then append the corresponding WHERE clause to the query. Something in the form of the following:
$mysqli = new mysqli(...);
$sql = 'SELECT * FROM table WHERE ';
$where = array();
$values = array();
$types = '';
if (!empty($_POST['name'])) {
$where[] = 'name = ?';
$values[] = $_POST['name'];
$types .= 's';
}
if (!empty($_POST['sex'])) {
$where[] = 'sex = ?';
$values[] = $_POST['sex'];
$types .= 's';
}
...
$sql .= implode(' AND ',$where);
$values = array_unshift($values, $types);
$statement = $mysqli->prepare($sql);
call_user_func_array(array($statement, 'bind_param'), $values);
...
精彩评论