在codeigniter中访问num_rows并返回到ajax

时间:2018-07-14 08:23:40

标签: php ajax codeigniter codeigniter-3 codeigniter-query-builder

这是我的模特:

public function fetch_customer_invoice($f_date,$t_date)
{
$this->db->select('invoice_id');
$this->db->from('invoice');
$this->db->where('date >=',$f_date);
$this->db->where('date <=',$t_date);
$res=$this->db->get();
 foreach($res->result() as $row)
 {
   $invoice=$row->invoice_id;
   $this->db->select('*');
   $this->db->from('invoice_products');
   $this->db->where('invoice_id',$invoice);
   $res=$this->db->get();
   return $res->result();
 }
}

这是我的控制器:

public function fetch_customer_invoice()
{
$from_date=$this->input->post('from_date');
$to_date=$this->input->post('to_date');
$data['res']=$this->revenue_reports_model- 
  >fetch_customer_invoice($from_date,$to_date);
echo json_encode($data);
}

脚本:

$('input[type="date"]').change(function() {
var from_date=$("#from_date").val();
var to_date=$("#to_date").val();
$.ajax({
    url: "<?php echo base_url(); ?>revenue_reports/fetch_customer_invoice/",
    dataType:'json',
    type: 'post',
    data : {"from_date" : from_date, "to_date" : to_date},
    success: function(data) {
      console.log(data.res);
    }
  });
}); 

此查询从发票表中获取特定日期的所有发票ID。在我的表中,从该特定日期开始有2行,但是模型仅返回第一行结果。为什么我不知道错误在哪里,无论是模型还是ajax函数中?请帮助。

1 个答案:

答案 0 :(得分:1)

希望这对您有帮助:

IN模型方法中,您的foreach应该是这样的:

public function fetch_customer_invoice($f_date,$t_date)
{
   $this->db->select('invoice_id');
   $this->db->from('invoice');
   $this->db->where('date >=',$f_date);
   $this->db->where('date <=',$t_date);
   $res = $this->db->get();
   foreach($res->result() as $row)
   {
      $invoice=$row->invoice_id;
      $this->db->select('*');
      $this->db->from('invoice_products');
      $this->db->where('invoice_id',$invoice);
      $res = $this->db->get();
      $data[] =  $res->result(); 
      /* Or better use $res->row() if only one record per id*/
  }
 return $data;
}

您可以使用count()这样的方法:

public function fetch_customer_invoice()
{
    $from_date=$this->input->post('from_date');
    $to_date=$this->input->post('to_date');
    $results = $this->revenue_reports_model->fetch_customer_invoice($from_date,$to_date);
    $data['res']= $results;
    //$data['count']= count($results);
    echo json_encode($data);
}