CodeIgniter Logo

Create a simple blog using CodeIgniter 2 – Part 1

Share this article

This entry will demonstrate to you on how to code a simple blog by using CodeIgniter 2. You may use whatever web server environment that you prefer such as Xampp, Lamp, Wamp, or Mamp. In this tutorial, I would like to use Wamp.

At the end of the tutorial, you should have a simple blog system with comment function. To download the complete source code, scroll down to the end of this tutorial. You also may want to view the final product first.

1. Setup a database

In the database named as blog, we will create a table, table ENTRY. The ENTRY table has columns such as entry_id, entry_name, entry_body, and entry_date (This is just a sample). The code is as below:

CREATE TABLE IF NOT EXISTS `entry` (
`entry_id` int(11) NOT NULL AUTO_INCREMENT,
`entry_name` varchar(255) NOT NULL,
`entry_body` text NOT NULL,
`entry_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`entry_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

2. Setup a database

Change the configuration and the database setting at config.php and database.php. You also need to set the encryption ke in order to use the database driver.

The configuration setting:

$config['base_url'] = 'http://localhost/blog/';
$config['index_page'] = '';
$config['encryption_key'] = 'KLIn!Psasaswewqsas3=zu0._BAU9dasdasd#!!@$.xdFJdVNRR';

The database setting:

$db['default']['hostname'] = 'localhost';
$db['default']['username'] = 'root';
$db['default']['password'] = '';
$db['default']['database'] = 'blog';

3. Create a new controller

In the controller folder, create a new controller file named as blog.php and the code as follow:

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Blog extends CI_Controller
{
    function __construct()
    {
        parent::__construct();
        $this->load->model('blog_model');
        $this->load->helper('url');
    }

    function index()
    {
        //this function will retrive all entry in the database
        $data['query'] = $this->blog_model->get_all_posts();
        $this->load->view('blog/index',$data);
    }

    function add_new_entry()
    {
        $this->load->helper('form');
        $this->load->library(array('form_validation','session'));

        //set validation rules
        $this->form_validation->set_rules('entry_name', 'Title', 'required|xss_clean|max_length[200]');
        $this->form_validation->set_rules('entry_body', 'Body', 'required|xss_clean');

        if ($this->form_validation->run() == FALSE)
        {
            //if not valid
            $this->load->view('blog/add_new_entry');
        }
        else
        {
            //if valid
            $name = $this->input->post('entry_name');
            $body = $this->input->post('entry_body');
            $this->blog_model->add_new_entry($name,$body);
            $this->session->set_flashdata('message', '1 new entry added!');
            redirect('blog/add_new_entry');
        }
    }
}

/* End of file blog.php */
/* Location: ./application/controllers/blog.php */

4. Create the model for the blog.

I named it as blog_model.php. Take note that the class name must start with a capital letter.

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Blog_model extends CI_Model
{
    function __construct()
    {
        parent::__construct();
        $this->load->database();
    }

    function get_all_posts()
    {
        //get all entry
        $query = $this->db->get('entry');
        return $query->result();
    }

    function add_new_entry($name,$body)
    {
        $data = array(
            'entry_name' => $name,
            'entry_body' => $body
        );
        $this->db->insert('entry',$data);
    }
}

/* End of file blog_model.php */
/* Location: ./application/models/blog_model.php */

5. Create the view files.

We need to create two view files for the index and add new entry page.

The index code:

<!DOCTYPE html>
<html>
  <head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>Blog</title>
</head>

<body>
  <h2>This is my blog</h2>
  <?php $this->load->view('blog/menu'); if($query):foreach($query as $post):?>
  <h4><?php echo $post->entry_name;?> (<?php echo $post->entry_date;?>)</h4>
  <?php echo $post->entry_body;?>
  <?php endforeach; else:?>
  <h4>No entry yet!</h4>
  <?php endif;?>
</body>
</html>

The add new entry code:

<!DOCTYPE html>
<html>
  <head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>Blog</title>
</head>

<body>
  <h2>Add new entry</h2>
  <?php echo validation_errors(); ?>
  <?php if($this->session->flashdata('message')){echo $this->session->flashdata('message');}?>
  <?php $this->load->view('blog/menu'); echo form_open('blog/add_new_entry');?>
  <p>Title:<br />
  <input type="text" name="entry_name" />
  </p>
  <p>Body:<br />
  <textarea name="entry_body" rows="5" cols="50" style="resize:none;"></textarea>
  </p>
  <input type="submit" value="Submit" />
  <?php echo form_close();?>
</body>
</html>

So, up to this point, you can write and add a new entry to the blog. Hooreyyy!!! 😀

You may download the full source code by clicking the link to download the files.

To be continued in part 2.

P/s: This tutorial was written and published in March 2011.

2 thoughts on “Create a simple blog using CodeIgniter 2 – Part 1”

Comments are closed.