在CodeIgniter中移除查询绑定中的“”

ewm0tg9j  于 2022-12-07  发布在  其他
关注(0)|答案(1)|浏览(80)

如果最小值和最大值为空,则将其更改为“price”

$post['min'] == NULL ? $post['min'] = 'price' : '';
$post['max'] == NULL ? $post['max'] = 'price' : '';

但是当我在查询中包含它时

$query = "SELECT * FROM items WHERE item_name LIKE ? AND price BETWEEN ? AND ? ORDER BY price ?";
$values = array(
    $this->security->xss_clean('%' . $post['item_name'] . '%'), 
    $this->security->xss_clean($post['min']), 
    $this->security->xss_clean($post['max']), 
    $this->security->xss_clean($post['order_by'])
);
$result = $this->db->query($query, $values)->result_array();

它抛出一个数据库错误,表示:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''ASC'' at line 1

如何删除查询绑定中的''

q8l4jmvw

q8l4jmvw1#

您的查询并不太复杂,所以我建议使用活动记录。使用条件调用的where()方法来添加筛选逻辑。
我还没有测试下面的建议,它假设所有四个元素都存在于$post数组中。
我不认为用奇怪的price >= priceprice <= price逻辑来扩充查询是有意义的--如果列检查没有价值,就省略它。
推荐的建模方法:

public function getItemsLikeBetween(array $post): array
{
    if (strlen($post['min'])) {
        $this->db->where('price >=', $post['min']);
    }
    if (strlen($post['max'])) {
        $this->db->where('price <=', $post['max']);
    }
    return $this->db
           ->like('item_name', $post['item_name'])
           ->order_by($post['order_by'])
           ->get('items')
           ->result_array();
}

相关问题