我的查询没有返回正确的计数

时间:2014-04-04 05:23:29

标签: php mysql sql codeigniter

我真的看不出问题出在哪里。

EX:宝马在纽约(city_id = 5)和康涅狄格州(city_id = 3)有售,所以当用户在搜索框中输入BMW时,它会返回2个结果1。

public function search_result_count($search) {
    $count=0;

    $search = addslashes($search);

    $city_id = $this->tank_auth->get_user_city()->id;

    $sql="select count(id) as count from ".$this->table_name."

          where   title LIKE  '%$search%' or zipcode like '%$search%'

          and city_id ='$city_id' ";

    $query=$this->db->query($sql);

    if($row=$query->row()) {

    $count=$row->count;

    }

    return $count;
 } 

即使我分配$ city_id =“5”仍然是一样的,这里会出现什么问题?

4 个答案:

答案 0 :(得分:1)

尝试使用GROUP BY,你错过了

$sql="select count(id) as count from ".$this->table_name."

         where   ((title LIKE  '%$search%' or zipcode like '%$search%')

         and city_id ='$city_id') GROUP BY $BMW_COL ";

宝马领域名称

答案 1 :(得分:1)

(city_id ='$city_id')语句的第一部分将跳过OR条件。试试这个

$sql="select count(id) as count from ".$this->table_name."

      where   ((title LIKE  '%$search%') and (city_id ='$city_id')) 

                                      or 

              ((zipcode like '%$search%') and (city_id ='$city_id')) ";

答案 2 :(得分:1)

尝试CI格式

$this->db->select('count(id) as count');
    $this->db->from('$this->table_name');
    $this->db->where('city_id', $city_id);
    $this->db->where("title LIKE  '%".$search."%' or zipcode like '%".$search."%'");
    $query = $this->db->get();
    if($query->num_rows() > 0){
            return $query->result_array();
        }
    }

答案 3 :(得分:0)

select count(id) as count from ".$this->table_name."

              where   (title LIKE '%$search%' or zipcode like '%$search%')

              and (city_id ='$city_id)