First time!
I'm learning Code Igniter, and as my first project I'm rewriting an existing site in CI.
On the existing site, all pages, dynamic or static, use a PHP include to load sidebar.php which is populated from the categories table in the database.
<div id="sidebar">
<?php
$result = mysql_query('SELECT category_id, name, url FROM categories ORDER BY category_id ASC');
while ($row = mysql_fetch_array($result)) {
$name=$row['name'];
$url=$row['url'];
print "<p><a href=\"category/$url\">$name</a></p>";
}
?>
</div>
So now I've started in CI, I figured that the way to go was to make a sidebar model with the database call, a sidebar controller, a sidebar view, and then to load this view in the default page controller.
So, in /application/models I've got sidebar_model.php
<?php
class Sidebar_model extends CI_Model {
public function __construct()
{
$this->load->database();
}
public function get_categories()
{
$query = $this->db->get('categories');
return $query->result();
}
}
Then in applications/controllers there is sidebar.php
<?php
class Sidebar extends CI_Controller {
public function __construct()
{
parent::__construct();
}
public function index()
{
$this->load->model('sidebar_model');
$data['result'] = $this->sidebar_model->get_categories();
$this->load->view('templates/sidebar_view', $data);
}
}
And then in applications/views/templates there is sidebar_view.php
<div id="sidebar">
<?php foreach($result as $row): ?>
<p><?php echo $row['name'] ?></p>
<?php endforeach ?>
</div>
This is called from my main page controller -
<?php
class Pages extends CI_Controller {
public function view($page = 'home')
{
if ( ! file_exists('application/views/pages/'.$page.'.php'))
{
// Whoops, we don't have a page for that!
show_404();
}
$data['title'] = ucfirst($page); // Capitalize the first letter
$this->load->view('templates/header', $data);
$this->load->view('pages/'.$page, $data);
$this->load->view('templates/sidebar_view', $data);
$this->load->view('templates/footer', $data);
}
}
The trouble I'm having is that whilst the page controller is obviously loading the sidebar view (the box is showing with the correct CSS styling) it's throwing up PHP errors.
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: result
Filename: templates/sidebar_view.php
Line Number: 2
Can anyone point me in the right direction here? Whilst just using a php include for the sidebar would be quick and easy, it doesn't seem like the MVC way of doing things.
Apologies for the lengthy post, and thanks in advance!