如果条件进入类mysql查询,则插入WHERE。

时间:2015-08-05 23:44:31

标签: php mysql

您好我如何转换以下查询,因此我没有给出错误:可捕获的致命错误:

Object of class pagination could not be converted to string

$paginate = new pagination($page, 'SELECT * FROM properties WHERE 1', $options);


            if (!empty($sector)) { $paginate .= " AND sector = :sector"; }
            if (!empty($property_type))  { $paginate .= " AND property_type = :property_type"; }
            if (!empty($contract))  { $paginate .= " AND contract = :contract"; }
            if (!empty($minimum_price))  { $paginate .= " AND price BETWEEN :minimum_price AND :maximum_price"; }
            if (!empty($m2_from))  { $paginate .= " AND m2 BETWEEN :m2_from AND :m2_until"; }
            if (!empty($contract))  { $paginate .= " AND bedrooms = :bedrooms"; }

1 个答案:

答案 0 :(得分:1)

$ paginate 是类分页的对象变量,因此其变量类型为object。我先构建查询然后创建对象。

所以我们在这里做的是创建查询的字符串变量并使用defaut SELECT查询进行分配。然后我们运行if statements然后我们构建它,这样你就不会尝试将字符串添加到对象类型。

$query= "SELECT * FROM properties WHERE 1";

        if (!empty($sector)) { $query .= " AND sector = :sector"; }
        if (!empty($property_type))  { $query.= " AND property_type = :property_type"; }
        if (!empty($contract))  { $query .= " AND contract = :contract"; }
        if (!empty($minimum_price))  { $query .= " AND price BETWEEN :minimum_price AND :maximum_price"; }
        if (!empty($m2_from))  { $query .= " AND m2 BETWEEN :m2_from AND :m2_until"; }
        if (!empty($contract))  { $query .= " AND bedrooms = :bedrooms"; }

$paginate = new pagination($page, $query, $options);

修改1

您的SELECT查询也不正确。您在WHERE子句之后错过了列名称。