根据可选的表单输入搜索MySQL表

时间:2013-11-25 00:20:12

标签: php mysql mysqli

我正在尝试为我的客户系统编写一个函数,该函数可以根据搜索表单中的一个(或多个)输入搜索“customers”表。代码发布在

下面
$lookupCust['userid'] = mysqli_real_escape_string($mysqli, $_POST['userid']);
$lookupCust['name'] = mysqli_real_escape_string($mysqli, $_POST['name']);
$lookupCust['phone'] =  mysqli_real_escape_string($mysqli, $_POST['phone']);
$lookupCust['balance'] =  mysqli_real_escape_string($mysqli, $_POST['balance']);
$lookupCust['credit'] =  mysqli_real_escape_string($mysqli, $_POST['credit']);
$lookupCust['notes'] = mysqli_real_escape_string($mysqli, $_POST['notes']);

$query = "SELECT * FROM customers WHERE 
            userid = '" . $lookupCust['userid'] . "' OR
            name = '" . $lookupCust['name'] . "' OR
            phone = '" . $lookupCust['phone'] . "' OR
            balance = '" . $lookupCust['balance'] . "' OR
            credit = '" . $lookupCust['credit'] . "' OR
            notes = '" . $lookupCust['notes'] . "'";
$lookupCust['result'] = '<table border="1"><tr><td>Username</td><td>Name</td><td>Phone</td><td>Balance</td><td>Credit</td><td>Notes</td></tr>';

while($row = mysqli_fetch_assoc($result))
    $lookupCust['result'] .= "<tr><td>".$row['userid']."</td><td>".$row['name']."</td><td>".$row['phone']."</td><td>".$row['balance']."</td><td>".$row['credit']."</td><td>".$row['notes']."</td></tr>";

这里的问题是,无论输入什么内容,由于查询有空格(来自未填写的字段),所有客户都将被列出。有人可以写一个关于如何只搜索提交给查询的内容的例子吗?

2 个答案:

答案 0 :(得分:2)

这样的代码:

$where = "";

foreach ($_POST as $k => $v)
{
    if ($v == "")
        continue;

    if ($where != "")
        $where .= "OR ";

    $where .= $k ." = '".mysqli_real_escape_string(trim($v))."'";
}

如果$_POST不是搜索关键字。你可以这样做:

$search = Array('userid', 'name', 'phone', 'balance', 'credit', 'notes');

$where = "";

foreach ($search as $col)
{
    if ($_POST[$col] == "")
        continue;

    if ($where != "")
        $where .= "OR ";

    // $where .= $col ." LIKE '".mysqli_real_escape_string(trim($_POST[$col]))."%'"; // prefix matching

    // $where .= $col ." LIKE '%".mysqli_real_escape_string(trim($_POST[$col]))."%'"; //   matches anywhere
}

仅供参考,我认为通过POST方法搜索并不是一个好习惯。难以建立永久链接网址。这不是用户友好的。

答案 1 :(得分:1)

使用&&AND条件,例如:

$query = "SELECT * FROM customers WHERE 
  userid = '{$lookupCust['userid']}' && userid != '' ||
  name = '{$lookupCust['name']}' && name != '' ||
  phone = '{$lookupCust['phone']}' && phone != '' ||
  balance = '{$lookupCust['balance']}' && balance != '' || 
  credit = '{$lookupCust['credit']}' && credit != '' ||
  notes = '{$lookupCust['notes']}' && notes != ''";

我冒昧地用双引号向您展示一种技巧来节省击键。此外,您应该确保检查mysqli_result::$num_rows。在该链接上有一个很好的OOP风格示例。但是,您应该将数据库连接保存在安全的单独页面上。