2

I want to display a list of results from my database. Currently, my view is only displaying the last row my query retrieves. What am I missing here? Thanks for any help you can give.

Model:

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

Controller:

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);
}

View:

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

3 回答 3

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();
}
于 2013-09-11T20:24:32.237 回答
1

应该是这样的。

$data[] = $agency;

您不需要解析值机构。CodeIgniter 为您完成

$data['agencies'] = $agency;

试试看。

于 2013-09-11T20:14:55.437 回答
1

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

将其更改为:

$data[] = $agency;

或者:

array_push($data, $agency);

希望这可以帮助!

于 2013-09-11T20:01:32.047 回答