繁体   English   中英

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

[英]CodeIgniter Query Results Only Displays Last Row in View

我想显示数据库中的结果列表。 当前,我的视图仅显示查询检索的最后一行。 我在这里想念什么? 谢谢你提供的所有帮助。

模型:

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;?>

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

更改为:

$data[] = $agency;

要么:

array_push($data, $agency);

希望这可以帮助!

应该是这样。

$data[] = $agency;

您不需要解析价值代理商.CodeIgniter会为您完成

$data['agencies'] = $agency;

试试吧。

控制器:

(...)
$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();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM