具有多个条件的搜索功能 - PHP / MySQL

时间:2022-09-25 16:39:26

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 !

编辑我不是要求检查至少一个选项有值[js验证],我要求查询!我会用mysqli准备好的声明!

1 个解决方案

#1


2  

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:

您可以检查特定字段的帖子是否为空,如果不是,则将相应的WHERE子句附加到查询中。以下形式的东西:

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

#1


2  

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:

您可以检查特定字段的帖子是否为空,如果不是,则将相应的WHERE子句附加到查询中。以下形式的东西:

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