When I try to run the following application in CodeIgniter, I get the following error:
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: data
Filename: views/blog.php
Line Number: 1
I've been trying to figure it out for almost an hour and I can't get it to work. My view looks like this:
<?php foreach($data->result() as $row): ?>
<h1><?php echo $row->title; ?></h1>
<p><?php echo $row->post; ?></p>
<?php endforeach; ?>
My controller looks like this:
<?php
class Blog extends CI_Controller {
public function index()
{
$this->load->database();
$data = $this->db->get('posts');
$this->load->helper('url');
$this->load->view('header');
$this->load->view('blog', $data);
$this->load->view('footer');
}
}
Anyone know how to fix this?
You have to change your controller and view
the array you send throught data should be like this:
$data['post'] = $this->db->get('posts');
and in your view:
<?php foreach($post->result() as $row): ?>
<h1><?php echo $row->title; ?></h1>
<p><?php echo $row->post; ?></p>
<?php endforeach; ?>
codeiginter sends variables to view using $data array. If you want to send something to a view, put inside to $data as $data['key'] = $val;
Try to use $blog
instead of $data
in the first line of your view.
I'm not sure but you assign $data
to a key called blog
in your controller...
The variables must be passed to the view as key-value pairs inside an array. Here this is explained.
I think the error notice is not originating on your controller but on your view (blog.php). You forgot to pass $data to the view. You should restructure the variable being passed to your view to something like this:
$data['data'] = $this->db->get('posts');
$this->load->view('blog', $data);
please structure your post model like this
public function __construct()
{
$this->load->database();
}
public function get_posts(){
$query=$this->db->get('posts');
return $query->result_array();
}
}
and your post controller like this
public function index()
{
$data['posts']=$this->Post_model->get_posts();
$this->load->view('templates/header');
$this->load->view('posts/index.php', $data);
$this->load->view('templates/footer');
}
and in your view file echo content this way :)
<?php foreach($posts as $post): ?>
<h3><?php echo $post['post_title'];?></h3>
<small><?php echo $post['post_date'];?></small>
<p><a href="<?php echo site_url('/posts/'.$post['post_title']);?>">Read more</a></p>
<?php endforeach;?>