sql和PHP中的多个部分搜索语句

时间:2014-10-30 20:36:05

标签: php mysql mysqli

我目前正在使用以下输入搜索创建一个简单的人mySQL搜索:

status(这是一个固定值为1,2,3,4的选项列表) 名字 姓 电子邮件 电话 描述

这是我目前的代码:

if($stmt = $db_connect->prepare("SELECT * FROM candidate WHERE status = ?
OR firstname = ?
OR surname = ?
OR email = ?
OR telephone_mobile = ?
OR description = ?"))
{
   $stmt->bind_param('isssis',$post_status, $post_firstname, $post_surname, $post_email, $post_phone, $post_desc);
   $stmt->execute();
   $main = $stmt->num_rows;
   $result = $stmt->get_result();
}

<table>
<?php 
while($row = $result->fetch_object()) {
?>
<tr>
<td><?php echo $row->firstname; ?></td>
<td><?php echo $row->surname; ?></td>
<td><?php echo $row->email; ?></td>
<td><?php echo $row->telephone_mobile; ?></td>
<td><?php echo $row->description; ?></td>
</tr>
<?php } $stmt->free_result(); ?>
</table>

我理解OR声明不正确,我一直在阅读有关AGAINSTLIKE声明的内容,而且我不确定正确的方法,因为有时某些输入表格可能是空白的,其他表格可能完全填写。

任何帮助都会很棒! :)

编辑:

Example Data

firstname | surname | email           | phone         | description
--------------------------------------------------------------------------------
john      | smith   | john@me.com     | 07645362839   | he has a SIA licence
larry     | howden  | lh@google.com   | 01574830487   | he is a beautiful man
jane      | jones   |                 | 01937437384   | has no email address

2 个答案:

答案 0 :(得分:1)

我认为很多评论都很有帮助,但并不是真的需要。

如果您想使用LIKE,只需更改您的查询:

SELECT * FROM candidate WHERE status LIKE 'status' OR firstname LIKE 'firstname'...

您可以使用LIKE代替等号。如果要包含元字符,可以使用%

答案 1 :(得分:1)

试试这个:

if(!empty($post_status)) {
    $binds[] = &$post_status;
    $bind_type .= "i";
    $criteria[] = 'status = ?';
}
if(!empty($post_firstname)) {
    $post_firstname_val = "%".$post_firstname."%"; 
    $binds[] = &$post_firstname_val;
    $bind_type .= "s";
    $criteria[] = 'firstname LIKE ?';
}
if(!empty($post_surname)) {
    $post_surname_val = "%".$post_surname."%";
    $binds[] = &$post_surname_val;
    $bind_type .= "s";
    $criteria[] = 'surname LIKE ?';
}
if(!empty($post_email)) {
    $post_email_val = "%".$post_email."%";
    $binds[] = &$post_email_val;
    $bind_type .= "s";
    $criteria[] = 'email LIKE ?';
}
if(!empty($post_phone)) {
    $post_phone_val = "%".$post_phone."%";
    $binds[] = &$post_phone_val;
    $bind_type .= "s";
    $criteria[] = 'phone LIKE ?';
}
if(!empty($post_desc)) {
    $post_desc_val = "%".$post_desc."%";
    $binds[] = &$post_desc_val;
    $bind_type .= "s";
    $criteria[] = 'description LIKE ?';
}
if(count($criteria) > 0) {
    $query .= ' WHERE '.implode(" OR ", $criteria);
}

$stmt = $db_connect->prepare($query);
if(count($binds) > 0) {
    $params = array_merge(array($bind_type), $binds);
    call_user_func_array(array($stmt, 'bind_param'), $params);
}
$stmt->execute();

对于每个非空搜索条件,它将添加一个条件以部分匹配该条件(如果输入整个值,则添加完整条件)。 这将返回与添加到搜索中的任何条件匹配的所有行。

假设您有$post_firstname = "Jane"$post_pone = "0764536"

代码将返回第1行(因为它将部分匹配手机)和第4行,因为它将完全匹配名称。