Search feature with multiple criteria - PHP/MySQL

放肆的年华 提交于 2020-01-15 05:11:08

问题


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
i am not asking for checking atleast a single option has value [js validation], i am asking for the query !
I'll use mysqli prepared statement !


回答1:


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);
...


来源:https://stackoverflow.com/questions/6035983/search-feature-with-multiple-criteria-php-mysql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!