CodeIgniter未定义变量:新闻PHP

时间:2014-03-09 16:35:42

标签: php codeigniter

我收到这些错误/警告:

A PHP Error was encountered

Severity: Notice

Message: Undefined variable: news

Filename: news/index.php

Line Number: 1

A PHP Error was encountered

Severity: Warning

Message: Invalid argument supplied for foreach()

Filename: news/index.php

Line Number: 1

我按照CodeIgniter网站中的用户指南进行操作。

这些是我使用的代码:

News_model.php

 <?php
class News_model extends CI_Model {

    public function __construct()
    {
        $this->load->database();
    }


    public function get_news($slug = FALSE)
    {
        if ($slug === FALSE)
        {
            $query = $this->db->get('news');
            return $query->result_array();
        }

        $query = $this->db->get_where('news', array('slug' => $slug));
        return $query->row_array();
    }


}

News.php

<?php 

class News extends CI_Controller {

     public function __construct() {
          parent::__construct();
          $this->load->model('news_model');
     }


     public function index() {
          $data['news'] = $this->news_model->get_news();
          $data['title'] = 'News archive';

          $this->load->view('templates/header', $data);
          $this->load->view('news/index', $data);
          $this->load->view('templates/footer');
     }

     public function view($slug) {
          $data['news_item'] = $this->news_model->get_news($slug);
          if(empty($data['news_item'])) {
           show_404();
          }

          $data['title'] = $data['news_item']['title'];

     }

}

index.php (VIEW)

<?php foreach ($news as $news_item): ?>

    <h2><?php echo $news_item['title'] ?></h2>
    <div id="main">
        <?php echo $news_item['text'] ?>
    </div>
    <p><a href="news/<?php echo $news_item['slug'] ?>">View article</a></p>

<?php endforeach ?>

view.php

<?php
echo '<h2>'.$news_item['title'].'</h2>';
echo $news_item['text'];

echo "Hello";   

为什么我收到错误的任何想法?非常感谢帮助。感谢。

更新

我删除了渲染功能。现在,当我去查看新闻时,它是空的,没有显示任何记录。

观看目录结构:

  
      
  • 新闻   
        
    • 的index.php
    •   
    • view.php
    •   
  •   
  • 页   
        
    • about.php
    •   
    • home.php
    •   
  •   
  • 模板   
        
    • footer.php
    •   
    • 的header.php
    •   
  •   

0 个答案:

没有答案