【问题标题】:Codeigniter View returns only last row queryCodeigniter 视图仅返回最后一行查询
【发布时间】:2013-07-04 15:26:52
【问题描述】:

我是 CI/PHP/开发新手。我坚持这个问题。这似乎是非常基本的,但我就是不能正确!

问题是我的视图只会显示查询结果的最后一行

型号:

$this->db->select('Caption,Description');                           
$query = $this->db->get_where('Events', array ('User_iduser' => $user_id));
$results = $query->result();                            

控制器:

$this->load->model('get_events_model');
$data['results'] = $this->get_events_model->get_events(); 
$this->load->view('main/members_area_form',$data);

查看:

<?php foreach($results as $row); {
echo $row->Caption;
echo $row->Description;
}
?>

为了解决问题,我已经提出:

var_dump($results);

...在视图中,结果是:

array(3) { [0]=> object(stdClass)#18 (2) { ["Caption"]=> string(5) "Color"     ["Description"]=> string(4) "Blue" } [1]=> object(stdClass)#19 (2) { ["Caption"]=> string(5) "Color" ["Description"]=> string(3) "Red" } [2]=> object(stdClass)#20 (2) { ["Caption"]=> string(5) "Color" ["Description"]=> string(5) "Black" } } 

所以 db 查询没有任何问题,但 foreach 循环仍然只显示查询的最后一行。我做错了什么?

【问题讨论】:

    标签: codeigniter codeigniter-2


    【解决方案1】:
    remove ";" from 
    <?php foreach($results as $row); {
    
    the line will be 
    <?php foreach($results as $row) {
    
    in your case foreach was only looping but your echos was not in foreach.
    after executing foreach 
    it was coming to your echo part and echoing last row as foreach already conpleted its loop.
    

    【讨论】:

    • 是的,就是这样。它现在起作用了,这一切都说得通。谢谢
    【解决方案2】:

    看看你的视图代码:

    您应该删除不必要的分号“;” 在foreach之后

    <?php 
         foreach($results as $row) {
            echo $row->Caption;
            echo $row->Description;
         }
    ?>
    

    【讨论】:

      猜你喜欢
      • 2013-09-16
      • 1970-01-01
      • 2017-05-12
      • 1970-01-01
      • 2018-08-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-01
      相关资源
      最近更新 更多