I saw plenty of questions and tried all those fixes similar to this issue but could not get this resolved. Please help.
I am following codeigniter news item tutorial. I displayed news from database. When I click on a link to view particular news it throws 404.
Here is the code:
Controller:
<?php
class News extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->model('news_model');
$this->load->helper('url');
}
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);
// var_dump($data);exit;
if (empty($data['news_item'])) {
show_404();
}
$data['title'] = $data['news_item']['title'];
$this->load->view('templates/header', $data);
$this->load->view('news/view', $data);
$this->load->view('templates/footer');
}
}
Model:
<?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();
}
}
View:
news.php
<?php
class News extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->model('news_model');
$this->load->helper('url');
}
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);
// var_dump($data);exit;
if (empty($data['news_item'])) {
show_404();
}
$data['title'] = $data['news_item']['title'];
$this->load->view('templates/header', $data);
$this->load->view('news/view', $data);
$this->load->view('templates/footer');
}
}
view.php
<?php
echo '<h2>' . $news_item['title'] . '</h2>';
echo $news_item['text'];
routes:
$route['news/(:any)'] = 'news/view/$1';
$route['news'] = 'news';
$route['(:any)'] = 'pages/view/$1';
$route['default_controller'] = 'pages/view';
Base url is blank in config.
CI version is 2.1.4 (latest)
This URL shows all the news items correctly - http://localhost/educon/index.php/news/
This URL throws 404 - http://localhost/educon/index.php/news/view/n1