Table of content

Your First Post

Do you have blog? Well, lets create a simple blog engine for our learning process.

First, let create new database called blog, and add table post.

CREATE TABLE  `post` (
`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`title` VARCHAR( 255 ) NOT NULL ,
`content` TEXT NOT NULL ,
`post_date` DATETIME NOT NULL ,
`comment_enable` BOOL NOT NULL
);

INSERT INTO `post` (`id`, `title`, `content`, `post_date`, `comment_enable`) VALUES
(1, 'Helllo!', 'This is sample post. Thanks you for reading.', '2009-10-08 06:52:36', 0);

Don't forget to set your configuration, such as in config.php, database.php, and autoload.php.

autoload.php
$autoload['libraries'] = array('database', 'session');
$autoload['helper'] = array('url');
config.php
$config['base_url']	= "http://localhost/cibook/";
database.php
$db['default']['username'] = "root"; // set with your database username
$db['default']['password'] = "root"; // set with your database password
$db['default']['database'] = "blog"; // set with your database name

Model

Add this model (post_model.php) to your model directory. It's has 1 function right now, but we'll add more functions the more we go with this tutorial.

<?php
class post_model extends Model {
    
    function get_posts()
    {
        $this->db->order_by("post_date", "desc"); 
        $query = $this->db->get('post');
        return $query->result();
    }    
}

?>

Controller

Lets create blog index, put this file (blog.php) in your controller directory. It has simple function to display all your posts from database.

<?php
class blog extends Controller {

    function __construct() {
        parent::__construct();
        $this->load->model('post_model');
    }
    
    function index()
    {
        $post_list = $this->post_model->get_posts();
        
        $data = array(
            'post_list' => $post_list
        );
    
        $this->load->view('blog/index', $data);
    }    
}
?>

View

Create blog folder under application/views, and create index.php

<html>
    <head>
        <title>Simple blog</title>
    </head>
    <body>
    <h1>Welcome to my blog</h1>
    <? if (isset($post_list)) : ?>
        <? foreach ($post_list as $post) : ?>
        <div class="post">
        <h2><?= $post->title ?></h2>
        <p><?= $post->content ?></p>
        <small><?= $post->post_date ?></small>
        </div>
        <? endforeach ?>
    <? else: ?>
        <div class="post">
        <p>No posts.</p>
        </div>
    <? endif ?>    
    </body>
</html>

It still has simple views, but you get the point. Go to http://localhost/cibook/index.php/blog/, you should see your first post.

add to del.icio.us