我在Apache xampp上使用Codeigniter並嘗試在視圖中第一次使用foreach,並且我無法使其工作。使用foreach的Codeigniter
我的控制器代碼:
class Test extends CI_Controller {
public function index($page = 'testv')
{
if (! file_exists(APPPATH.'/views/'.$page.'.php'))
{
show_404();
}
$this->load->model('testm');
$data['news'] = $this->testm->get_news();
$this->load->view('headder');
$this->load->view($page, $data);
$this->load->view('footer');
}
}
我的模型:
class Testm extends CI_Model {
public function __construct()
{
parent::__construct();
}
Public function get_news()
{
$query = $this->db->query('SELECT id, date, text FROM news');
foreach ($query->result_array() as $row)
{
echo $row['id'];
echo $row['date'];
echo $row['text'];
}
}
}
筆者認爲:
<main id='central_section'>
<section id='logo_section'>
<img src='<?php echo base_url(); ?>img/logo.png' id='small_logo' alt="Logo">
</section>
<section id='content'>
<p class="large_headding">News</p>
<?php foreach($news as $news) { ?>
<article class="article_text">
<p class="segment_headding"><?php echo $news->date; ?></p>
<?php echo $news->text; ?>
</article>
<?php } ?>
<div id="spacer"></div>
</section>
</main>
目前我得到以下警告消息:
A PHP Error was encountered
Severity: Warning
Message: Invalid argument supplied for foreach()
Filename: views/testv.php
Line Number: 18
Backtrace:
File: C:\xampp\htdocs\tsh\CI\application\views\testv.php
Line: 18
Function: _error_handler
File: C:\xampp\htdocs\tsh\CI\application\controllers\test.php
Line: 16
Function: view
File: C:\xampp\htdocs\tsh\public_html\index.php
Line: 292
Function: require_once
但是我的數據庫中的文本確實出現在頁面頂部的頁面頂部,所以我知道數據庫正在連接,並且正在收集它的數據。誰能告訴我我要去哪裏?
謝謝,對視圖文件進行一些調整,以改變<?php echo $ news-> date; ?> to <?php echo $ news ['date']; ?>這工作完美! – Tessa