[英]Selecting records from a database table in PHP using CodeIgniter and pass to a view
我正在使用CodeIgniter在PHP中進行查詢,以從數據庫中獲取所需的數據。 為了能夠獲取特定列的所有值,我將其存儲在數組中並將其傳遞到視圖中。 但是我只能在一欄上做。
這是我的代碼:
$query = $this->db->query('SELECT name, description FROM module');
$result = $query->result_array();
foreach ($result as $key => $rowdata) {
$resultdata['values'][$key] = $rowdata['name'];
}
$this->load->view('myview', $resultdata);
在這種情況下,我可以從模塊表中獲取所有名稱。 但是我的問題是,我也想在模塊表中獲取所有描述,但是我不知道如何實現它並將其傳遞到視圖中。 希望有人可以幫助我。 謝謝!
您沒有使用MVC模式!
首先,您應該在模型中編寫查詢!
然后像這樣將其加載到您的控制器中
$this->load->model('ModelName');
然后調用函數以獲取數據
$data = $this->modelname->functionToRetreiveData();
然后使用foreach遍歷數據
$dataToView = array();
foreach($data as $key=>$row)
{
$dataToView['something'][$key]['value'] = $row->name_of_column;
}
並將數組傳遞給視圖$ this-> load-> view('someview',$ dataToView);
然后在視圖中
foreach($value as $val):
<p><?php echo $val['name']?><p>
endforeach
您好,您將在控制器中執行兩次循環,然后在視圖中進行打印將其簽出
//在控制器中
$query = $this->db->query('SELECT name,description FROM module');
$resultdata['results'] = $query->result_array();
$this->load->view('myview',$resultdata);
myview.php
foreach($results as $result)
{
echo $result['name'],' ',$result['description'];
}
$query = $this->db->query('SELECT name,description FROM module');
$result = $query->result_array();
foreach($result as $rowdata){
$resultdata['values'][] = $rowdata;
}
$this->load->view('myview',$resultdata);
嘗試查看:
print_r($values);
您可能會有:
$result[0]['name'], $result[0]['description'] ...
$this->load->database();
$this->db->select('employee');
$query = $this->db->get();
return $query;
foreach ($query as $row) {
print $row->'Name';
.
.
.
print $row->'Address';
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.