[英]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.