CodeIgniter查询结果仅显示视图中的最后一行

时间:2013-09-11 19:59:39

标签: php mysql codeigniter templates foreach

我想显示数据库中的结果列表。目前,我的视图仅显示我的查询检索的最后一行。我在这里错过了什么?感谢您提供任何帮助。

型号:

public function get_agencies() {
    $this->db->select("AgencyNumber, AgencyName, users.id, active");
    $this->db->from('Agency, users');
    $this->db->where('users.id = Agency.id');
    $q = $this->db->get();

    if($q->num_rows() > 0) {
        foreach($q->result() as $agency) {
            $data['agencies'] = $agency;
        }
        return $data;
    }
}

控制器:

function modify_agency() {
    $this->load->model('ion_auth_model');
    $this->data['agencies'] = $this->ion_auth_model->get_agencies();

    //added the following 2 lines to load view with header and footer from template         
    $this->data['main_content'] = 'auth/modify_agency';
    $this->load->view('./includes/template', $this->data);
}

查看:

<?php foreach ($agencies as $agency):?>
    <tr>
        <td><?php echo $agency->AgencyNumber;?></td>
        <td><?php echo $agency->AgencyName;?></td>
        <td><?php if($agency->active == 1) { echo 'Active'; } else { echo 'Inactive'; };?></td>
    </tr>
<?php endforeach;?>

3 个答案:

答案 0 :(得分:1)

在您的模型中,您不是将$agency变量推送到数组中。它们在每次迭代时都被替换,因此$data['agencies']将只包含最后一次迭代的值。另外,正如Syed在上面回答的那样,您不需要在代码中包含数组索引值

将其更改为:

$data[] = $agency;

或:

array_push($data, $agency);

希望这有帮助!

答案 1 :(得分:1)

应该是这样的。

$data[] = $agency;

您无需解析代理商的代理商.CodeIgniter会为您执行此操作

$data['agencies'] = $agency;

试试吧。

答案 2 :(得分:1)

控制器:

(...)
$this->data['agencies'] = $this->ion_auth_model->get_agencies();
(...)
$this->load->view('./includes/template', $this->data);
(...)

型号:

(...)
if($q->num_rows() > 0) {
    foreach($q->result() as $agency) {
        $data['agencies'] = $agency;
    }
    return $data;
}

查看:

<?php foreach ($agencies as $agency):?>
(...)

请注意,如果get_agencies中没有单行,则表示您没有返回任何内容,并且您在视图中的foreach函数中会收到错误。

你可以这样回来:

public function get_agencies() {
    $this->db->select("AgencyNumber, AgencyName, users.id, active");
    $this->db->from('Agency, users');
    $this->db->where('users.id = Agency.id');
    $q = $this->db->get();

    return ($q->num_rows() > 0) ? $q->result() : array();
}
相关问题