首页 > 解决方案 > Codeigniter Where 子句不起作用

问题描述

Codeigniter Where 子句在使用变量时不起作用。如果我直接将数字用于 $price_min 这应该可以。

当我使用

$s=$this->db->where(' prize < ' , $price_max);

这将是回报

prize < [value] => '100' .

当我使用$s=$this->db->where(' prize < ' , 100);

这将返回

prize < [value] => 100 .

我想当我使用变量时,这个返回是字符串。如何将其更改为整数?
请按照我的代码

function filter()
{      
        $state = $this->input->post("state");
        $type = $this->input->post('type');
        $bed = $this->input->post('bed');
        $bath = $this->input->post('bath');
    echo    $price_min=$this->input->post("price-min");  //output: 5

    echo    $price_max=$this->input->post("price-max");  //output: 100
        $this->db->where(' prize > ' , $price_min);
    $s=$this->db->where(' prize < ' , $price_max); 
    print_r($s); 
        $filterquery = $this->db->get('details');
        $records= $filterquery->result();
        return array(
            'records' => $records,
            'count' => count($records),
        );

}

标签: sqlcodeigniter-3where-clause

解决方案


希望这对你有用:

function filter()
{      
    $state = $this->input->post("state");
    $type = $this->input->post('type');
    $bed = $this->input->post('bed');
    $bath = $this->input->post('bath');

    $price_min = $this->input->post("price-min");
    $price_max = $this->input->post("price-max");

    /*you can set 0 or whatever if post is empty i set null */
    $price_min = ! empty($price_min) ? intval($price_min) : NULL;
    $price_max = ! empty($price_max) ? intval($price_max) : NULL;

    /* you can also check with if statement
       if ($price_min != '' && $price_max != '') {
          $price_max  = intval($price_max);
          $price_min = intval($price_min);
          your where statement.....
       }
    */
    $this->db->where('prize >' , $price_min);
    $this->db->where('prize <' , $price_max);

    $filterquery = $this->db->get('details');
    $records = $filterquery->result();
    return array(
        'records' => $records,
        'count' => count($records),
    );
}

推荐阅读