How to Use Model For Parser? - El Forum - 05-02-2009
[eluser]Deep Arora[/eluser]
I have following code (from the docs) that I am trying out to get a feel of CI..
VIEW: blog_view.php
Code: <html>
<head>
<title>{blog_title}</title>
</head>
<body>
<h3>{blog_heading}</h3>
{blog_entries}
<h5>{post_title}</h5>
<p>{post_content}</p>
{/blog_entries}
</body>
</html>
CONTROLLER: blog.php
Code: <?php
class Blog extends Controller {
function Blog()
{
parent::Controller();
}
function index()
{
[b]$query = $this->db->query("SELECT * FROM site_posts");[/b]
$this->load->library('parser');
$data = array(
'blog_title' => 'My Blog Title',
'blog_heading' => 'My Blog Heading',
[b]'blog_entries' => $query->result_array()[/b]
);
$this->parser->parse('blog_view', $data);
//$this->load->view('blog_view', $data);
}
}
/* End of file blog.php */
/* Location: ./system/application/controllers/blog.php */
Now as you can see, I am using the SQL QUERY in the controller. But I want to use it in the MODEL. When I write a model as :
MODEL: blog_model.php
Code: class Blog_model extends Model {
function Blog_model()
{
// Call the Model constructor
parent::Model();
}
function get_last_ten_entries()
{
$query = $this->db->get('site_posts', 10);
return $query->result();
}
}
...what should I change the following lines in the controller to?
Code: [b]$query = $this->db->query("SELECT * FROM site_posts");[/b]
[b]'blog_entries' => $query->result_array()[/b]
I tried this:
Code: $this->load->model('Blog_model');
$result_set['blog_posts'] = $this->Blog_model->get_last_ten_entries();
[b]'blog_entries' => $result_set[/b]
but it didn't work..
Any help pls?
How to Use Model For Parser? - El Forum - 05-03-2009
[eluser]Yorick Peterse[/eluser]
Add the following code (don't forget to change it):
Controller
Code: <?php
class some_class extends Controller {
//Constructor function
function __construct() {
parent::Controller();
}
//Index function
function index() {
//Load the comments model
$this->load->model('comments_model');
//Get the comments
$data = array (
'result' => $this->comments_model->get_comments()
);
//Load the view
$this->load->view('some_view',$data);
}
}
?>
The model
Code: <?php
class Some_model extends Model {
//Function for the comments
function get_comments() {
//Create the query
$query = $this->db->get('comments');
//Check to see if there are any comments at all
if($query->num_rows() > 0) {
//Return the results
return $query->result();
}
//No comments
else {
show_error('No comments have been added yet');
}
}
?>
The view
Use a foreach loop as shown in the snippet, then use $row->database_column (e.g. $row->id) to output the result.
Code: <?php foreach($result as $row): ?>
<h3><?php echo $row->name; ?></h3>
<?php endforeach; ?>
|