【问题标题】:Codigniter query returning wrong countCodeigniter 查询返回错误计数
【发布时间】:2019-02-12 20:14:33
【问题描述】:

我正在使用代码点火器,并且正在构建一个查询以返回有多少人参加了活动。所以我可以取这个数字并试着算出一个百分比。

我遇到的问题是我正在尝试根据 Codeigniter 3 Docs 构建查询,但由于某种原因我返回了错误的结果,根本无法弄清楚原因。

首先是我正在查询的数据库中的表:

这是我从控制器调用的函数:

public function get_event_attendance_percentage($id) {
        $this->db->select('*');
        $this->db->from('attendance');
        $this->db->where('event_id', $id );
        $this->db->where('attended', 1 );
        $attendancecount = $this->db->get();
        return count($attendancecount);

    }

我从我的出勤表中选择所有,然后我声明我希望所有来自 id 17 的活动的出席,然后我还说明出席的位置 = 1

我想返回数字 3,但我返回的是数字 1。

谁能帮我看看哪里出错了?


在@Vickel 的感激帮助下,我完成了这项工作。以下是返回正确结果的查询:

public function get_event_attendance_percentage($id) {
        $this->db->select('*');
        $this->db->from('attendance');
        $this->db->where('event_id', $id );
        $this->db->where('attended', 1 );
        $attendancecount = $this->db->get();
        return $attendancecount->num_rows();
    }

【问题讨论】:

标签: jquery database codeigniter model


【解决方案1】:

count() 是一个php built-in function,在你使用它的方式中,它会“计算”查询字符串,因此无论如何都返回 1

正确的 CI 方式是使用return $attendancecount->num_rows():见here

【讨论】:

  • 嘿 Vickel,非常感谢您的好意建议,我确实已经尝试过了,但我收到一条错误消息:CI_DB_mysqli_result 无法转换为字符串?我需要将视图中的结果作为字符串回显。
  • 你是对的维克!我只是把它组织得有点不对劲。我将在我原来的问题中发布工作的 sn-p。感谢您花时间帮助我。我真的很感激!
  • 检查 echo $attendancecount->num_rows();die(); 如果行正确,其他错误可能是由于您如何继续处理退货
【解决方案2】:

如果您只想计算行数,您可以使用 $this->db->count_all_results(),如下所示。

public function get_event_attendance_percentage($id)
{
        $this->db->where('event_id', $id );
        $this->db->where('attended', 1 );
        $this->db->from('attendance');
        return $this->db->count_all_results();
}

查看 CodeIgniter 手册 => https://www.codeigniter.com/user_guide/database/query_builder.html?highlight=count_all#limiting-or-counting-results

注意:-

num_rows() :- 使用 num_rows() 你首先执行查询,然后你可以检查你得到了多少行。 在您需要表格数据时很有用。

count_all_results() :- 使用 count_all_results() 您可以获得查询将产生的行数,但不会给您实际的结果集。 当您只需要行数时很有用,即分页,显示编号。记录等。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-15
    • 1970-01-01
    相关资源
    最近更新 更多