如何使用表格正确过滤来自MySQL的结果?

时间:2018-09-24 10:12:19

标签: php mysql prepared-statement

过滤结果的正确方法是什么?到目前为止,我所得到的是可以输入名字,姓氏,电话和其他内容的表格。如何使语句忽略空的输入字段,而不是搜索空的值?

我使用的是预备语句,当我过滤内容时,我使用WHERE firstname = ? and lastname = ?,如果某些内容为空,则条件更改语句。如何防止在有条件的情况下执行数百条语句?

$stmt = $this->mysqli->prepare("SELECT * FROM cust");

    if(!empty($firstname) && !empty($lastname)) {
        $stmt = $this->mysqli->prepare("SELECT * FROM cust WHERE as_first = ? AND as_last = ?");
        $stmt->bind_param("ss", $firstname, $lastname);
    } else if(!empty($firstname) && empty($lastname)) {
        $stmt = $this->mysqli->prepare("SELECT * FROM cust WHERE as_first = ?");
        $stmt->bind_param("s", $firstname);
    } else if(empty($firstname) && !empty($lastname)) {
        $stmt = $this->mysqli->prepare("SELECT * FROM cust WHERE as_last = ?");
        $stmt->bind_param("s", $lastname);
    }

1 个答案:

答案 0 :(得分:2)

不幸的是,您应该编写自己的条件,例如:

$sql = 'SELECT...' // your original query
$sql .= !empty($phone) ? ' phone = :phone';

并手动绑定参数:

if (!empty($phone)) {
    $stmt->bindParam(':phone', '%'.$phone.'%', PDO::PARAM_STR);
}