查询仅在codeigniter中查找最后一个值

时间:2018-02-05 10:52:43

标签: php codeigniter

我是CI / PHP /开发的新手。我坚持这个问题。这似乎是非常基本但我不能正确! 在sql执行时,我只能返回最后一个值。

  

控制器

$data['leadd']= $this->dashboard_model->countt($this->session->userdata('user_id'));

     foreach ($data['leadd'] as $q) { $date = $q['followup_date'];

     $data['lead']= $this->dashboard_model->lead_count($this->session->userdata('user_id'),$date); }

     $data['count'] = count($data['lead']);
  

模型

public function countt($userid)
{
    $sql = $this->db->query("SELECT followup_date FROM tg_partner_data WHERE assign_to = '$userid' AND active = 'Y'");

    return $sql->result_array();
}

public function lead_count($userid,$date)
{   
    $sql1 = $this->db->query("SELECT * FROM tg_partner_data
                             WHERE assign_to = '$userid' AND followup_date = '$date'
                             AND active='Y'");
    //echo $this->db->last_query();

    return $sql1->result_array();
}

1 个答案:

答案 0 :(得分:1)

首先,通过执行以下操作从一个表中选择所有后续日期:" SELECT followup_date FROM tg_partner_data WHERE assign_to =' $ userid' AND active =' Y'"。

然后对于每个followup_date,您执行另一个查询,但是您没有合并prevoius结果只是在foreach循环中覆盖它们。

Foreach循环应如下所示:

$data['lead'] = array();
foreach ($data['leadd'] as $q) { 
    $date = $q['followup_date'];
$data['lead'][] = $this->dashboard_model->lead_count($this->session->userdata('user_id'),$date));
}

您还可以重写SQL查询:     SELECT COUNT(*)FROM tg_partner_data WHERE assign_to =' $ userid'和followup_date =' $ date' AND active =' Y'"

它允许您直接从DB获取行数。