开发者

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

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 !


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜