具有执行数组参数的灵活搜索选项

时间:2018-05-21 15:40:49

标签: php pdo

我正在尝试制作一个灵活的搜索选项但是params在执行数组中没有用。我可以帮忙解决这个问题吗?

$extra = '';
$params = array();

$sql = "SELECT brand_id,brand_status,brand_name FROM brands ORDER BY brand_name";

$brand_status = "";
$brand_name = "su";

if($brand_status) {
    $extra .= "brand_status=:brand_status and ";
    $params[] = array(
        "brand_status" => $brand_status
    );
}
if($brand_name) {
    $extra .= "brand_name LIKE :brand_name and ";
    $params[] = array(
        "brand_name" => "%" . $brand_name . "%"
    );
}

if(count($params) > 0) {
    if(strlen($extra) > 0) {
        $extra = substr($extra, 0, -5);
    }
    $sql = "SELECT brand_id,brand_status,brand_name FROM brands WHERE $extra ORDER BY brand_name";
    $query = $db->prepare($sql);
    $result = $query->execute(array(
        $params
    ));
} else {
    $result = $query = $db->query($sql);
}

if($result)
    $num = $query->rowCount();
if($num > 0) {
    while($row = $query->fetch()) {
        echo $row['brand_name'] . "<br>";
    }
}

如果brand_name值为空代码,则运行良好。我可以使用执行数组参数执行灵活的搜索选项,而无需使用bindParam或bindValue吗?

1 个答案:

答案 0 :(得分:0)

Nigel Ren,marekful和user3783243非常感谢您的答案和想法。

无法使用:execute($params)

使用过:params['brand_status'] = $brand_status

并且好主意:rtrim($extra, ' and ')

注意:我应该像这样回答我的问题,或者我应该用答案编辑我的问题?如果我对此感到抱歉。