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

标签 php mysql sql codeigniter

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

EX: 一辆 BMW 在纽约 (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"仍然是同样的东西,这里会有什么问题?

最佳答案

(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')) ";

关于php - 我的查询没有返回正确的计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22854217/

相关文章:

python - PHP 相当于 Python 的 __name__ == "__main__"?

php - 可以在 Dreamweaver 设计 View 中看到代码,但在浏览器中看不到

MySQL 5.7 间歇性最大连接错误

php - 检索多行的最后插入的 ID

mysql - 我可以在 SQL 语句中这样做吗?

javascript - 从 PHP 调用 Python 脚本

javascript - 在数据库中存储与使用 PHP 动态创建的表单不同的值?

mysql - 选择在mysql中加入多个表?

php - Symfony 配置 : Doctrine InvalidConfigurationException: Unrecognized option "options" under "doctrine.dbal"

SQL Server 'In' 语句项性能顺序