【问题标题】:Database query using CodeIgniter returning null values into array?使用 CodeIgniter 将空值返回到数组中的数据库查询?
【发布时间】:2013-07-01 18:23:19
【问题描述】:

我正在根据用户选择的日期从数据库中提取数字数据。出于某种原因,当我选择我的函数来提取今天的所有数据(没有数据)时,它仍然会形成一个空值数组。

我认为问题在于 select_sum() 或 where() 函数。这是我的 CI 查询:

    $this->db   
            ->select_sum('column1')
            ->select_sum('column2')
            ->select_sum('column3')
                ->where('created_at >=', date('Y-m-d'));
            $query = $this->db->get('table_name');

这是我的 foreach 循环,它将所有选定的数据拉入一个数组中,以便在整个页面中使用:

$popular_items_array = array();
        foreach ($query->result() as $key => $row) 
        {   
            if ($row == NULL) {
                echo "Error populating table.";
            } else {
             $popular_items_array = $row;
            }
        }

为了查看数据,我做了:

echo json_encode($popular_items_array);

结果显示:

{"column1":null,"column2":null,"column3":null}

如果我选择不同的时间范围(数据在设定日期之前实际存在),则相同的 JSON 回显将显示现有数据。我不明白的是,为什么查询返回任何东西?为什么不只是失败?以及如何运行检查/循环来捕获此问题,并显示一条错误消息,让用户知道该日期不存在数据?

【问题讨论】:

  • $this->db->last_query(); 是做什么的在 $query = $this->db->get('table_name'); 之后返回线?我很想看看实际的查询是什么样子的。
  • @DazzKnowles 查询看起来像这样 SUM(column1) AS column1, SUM(column2) AS column2, SUM(column3) AS column3 FROM (table_name) WHERE @987654329 @ >= '2013-07-01'

标签: php database arrays codeigniter


【解决方案1】:

如果您不希望得到任何记录,您可以将您的代码修改为:

$this->db   
    ->select_sum('column1')
    ->select_sum('column2')
    ->select_sum('column3')
        ->where('created_at >=', date('Y-m-d'))
        ->having('count(*) > 0');
$query = $this->db->get('table_name');

【讨论】:

  • 嗯,所以添加“have()”将阻止查询通过,但我如何检查它是否失败?这才是真正的问题 - 显示这些总和查询是否真的在做任何相关的事情。
  • 修复了这个问题,我添加了一个 if 语句说 if(empty($popular_items_array)
【解决方案2】:

这就是聚合函数(如sum()avg()max() 等)的工作方式,它们将从结果集中返回聚合值。如果结果集是空的,他们将聚合它。这导致了很多confusionbugreports 但这应该是如何工作的,更详细的解释can be found at dba.stackexchange.com

您可以使用COALESCENULL 值替换为更有用的值,或者您可以添加count(),这样您就可以知道使用了多少行来生成sum()s。

奇怪的是,如果你添加一个组,它会像你期望的那样工作(至少使用 mysql):

SELECT sum(id) sum_id FROM `users` WHERE 0 # => array( array('sum_id' => null) )

但是:

SELECT sum(id) FROM `users` WHERE 0 GROUP BY null # => array()

【讨论】:

    猜你喜欢
    • 2013-02-22
    • 1970-01-01
    • 1970-01-01
    • 2022-06-23
    • 2019-12-04
    • 1970-01-01
    • 2011-04-09
    • 2023-04-03
    • 1970-01-01
    相关资源
    最近更新 更多