I’m stuck with a particular error in the News tutorial of CodeIgniter. I’m not sure why it’s not working. I’ve copied everything to the letter, and yet I keep getting this error when I try to visit a slug page (http://localhost/codeig/index.php/news/slug-2 for example):
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
Following are the various files.
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');
}
protected function render($data){
$this->load->view('templates/header', $data);
$this->load->view('news/index', $data);
$this->load->view('templates/footer');
}
public function index() {
$data['news'] = $this->news_model->get_news();
$data['title'] = 'News archive';
//print_r($data['news']); -- Working
$this->render($data);
$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'];
$this->render($data);
}
}
?>index.php
<?php foreach ($news as $news_item) {?>
<h2><?php echo $news_item['title'];?></h2>
<div id="main">
<?php echo $news_item['text'];?>
</div>
<a href="http://news/<?php">;?>"]View article</a>
<?php } ?>view.php
<?php
echo '<h2>' . $news_item['title'] . '</h2>';
echo $news_item['text'];
?>routes.php
$route['news/(:any)'] = 'news/view/$1';
$route['news'] = 'news';
$route['(:any)'] = 'pages/view/$1';
$route['default_controller'] = 'pages/view';I’ve been pulling my hair for the past two hours. Please help!!
Packet Tide owns and develops ExpressionEngine. © Packet Tide, All Rights Reserved.