Create a simple blog using CodeIgniter 2 – Part 3

CodeIgniter Logo

For this CodeIgniter tutorial, I will demonstrate how to add category to our post in the blog and how to use Ion_Auth as our authentication library. This is a continuation from the past tutorials which are Part 1 and Part 2. However, I do recommend to you to download and look at the full source code of this tutorial because my explanation here maybe too short/simple. You may view the demo for final product here: CodeIgniter Blog

I would like to remind you guys to use the latest CodeIgniter version for better functionalities and security. You can look at the CodeIgniter user guide on how to update your CodeIgniter framework. You also can download the latest stable Ion_Auth library at github.

The steps for Part 3 as follows:

1. Install the ion_auth library first.

You may refer to Ben Edmund website for online documentation or if you already downloaded the library package from github, you may find the documentation inside the package.

2. Add a new directory called admin in the views directory

In the admin directory, create 3 new files; index.php, add_new_entry.php, andadd_new_category.php. In index.php, you can copy the content from views > blog > index.php or anything. This page will served as the administrator dashboard.

Edit the function index() in auth controller so that it will load views/admin/index.php. So, your administrator dashboard link would be domain.com/auth/index.

function index()
{
    $data['title'] = 'Dashboard - '.$this->config->item('site_title', 'ion_auth');

    if (!$this->ion_auth->logged_in())
    {
        //redirect them to the login page
        redirect('auth/login', 'refresh');
    }
    elseif (!$this->ion_auth->is_admin())
    {
        //redirect them to the home page because they must be an administrator to view this
        redirect($this->config->item('base_url'), 'refresh');
    }
    else
    {
        // get user detail
        $data['user'] = $this->ion_auth->user()->row();
        $this->load->view('admin/index',$data);
    }
}

add_new_entry.php basically is just same as the one in the blog views folder but this time we will limit the access. Only administrator can add new entry. The content for add_new_category.php will be discuss later.

Open up the ion_auth config file. You may want to customize the settings such as the site title, admin email, etc. Then, test the login function. It should load the views > admin > index.php page.

3. Create 2 new tables in our database, named as entry_category and entry_relationships.

Entry_category table is for storing details about our category such as category name, category slug, etc. In entry_relationships, we will store records such as which category is related to the posts/entries.

--
-- Table structure for table `entry_category`
--

CREATE TABLE IF NOT EXISTS `entry_category` (
  `category_id` int(11) NOT NULL AUTO_INCREMENT,
  `category_name` varchar(150) NOT NULL,
  `slug` varchar(150) NOT NULL,
  PRIMARY KEY (`category_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ;

--
-- Table structure for table `entry_relationships`
--

CREATE TABLE IF NOT EXISTS `entry_relationships` (
  `relationship_id` int(11) NOT NULL AUTO_INCREMENT,
  `object_id` int(11) NOT NULL,
  `category_id` int(11) NOT NULL,
  PRIMARY KEY (`relationship_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ;

4. Add a new function called add_new_category() into the Blog controller.

public function add_new_category()
{
    $data['title'] = 'Add new category - '.$this->config->item('site_title', 'ion_auth');

    if( ! $this->ion_auth->logged_in() && ! $this->ion_auth->is_admin() ) // block un-authorized access
    {
        show_404();
    }
    else
    {
        $this->load->helper('form');
        $this->load->library(array('form_validation'));

        // set validation rules
        $this->form_validation->set_rules('category_name', 'Name', 'required|max_length[200]|xss_clean');
        $this->form_validation->set_rules('category_slug', 'Slug', 'max_length[200]|xss_clean');

        if ($this->form_validation->run() == FALSE)
        {
            //if not valid
            $this->load->view('admin/add_new_category',$data);
        }
        else
        {
            //if valid
            $name = $this->input->post('category_name');

            if( $this->input->post('category_slug') != '' )
                $slug = $this->input->post('category_slug');
            else
                $slug = strtolower(preg_replace('/[^A-Za-z0-9_-]+/', '-', $name));

            $this->blog_model->add_new_category($name,$slug);
            $this->session->set_flashdata('message', '1 new category added!');
            redirect('add-new-category');
        }
    }
}

So, this function basically will help us to add a new category into our database. Take note that we restrict the access to this function. Only administrator can add a new category.

5. Add a add_new_category() function into the Blog model.

function add_new_category($name,$slug)
{
    $i = 0;
    $slug_taken = FALSE;

    while( $slug_taken ==  FALSE ) // to avoid duplicate slug
    {
        $category = $this->get_category(NULL,$slug);
        if( $category == FALSE )
        {
            $slug_taken = TRUE;
            $data = array(
                'category_name'    => $name,
                'slug'            => $slug,
            );
            $this->db->insert('entry_category',$data);
        }
        $i = $i + 1;
        $slug = $slug.'-'.$i;
    }
}

Both of the functions are named same so that it is easy for us to identify the relationship between the functions and purpose of the functions. However, this function is related to query and database, compared to the previous add_new_category function.

6. Edit add_new_category.php in the views > admin directory.

<?php echo form_open('add-new-category');?>
    <p><label>Category Name</label>
    <input type="text" name="category_name" size="30" /></p>

    <p><label>Slug</label>
    <input type="text" name="category_slug" size="30" /></p>

    <br />    

    <input class="button" type="submit" value="Submit"/>
    <input class="button" type="reset" value="Reset"/>    

</form>

I only show here the add new category form segment of code because in my view file, it consists of many new variables, which may produced errors if you copy paste it from here. Please refer to the attachment for the full source code.

Next you can add a menu/link to our function to view the add new category page. Your add new category is accessible via domain.com/blog/add_new_category. Do add a custom url for add new category in route.php config if you want.

Test your add new category function by adding some categories such as tutorial, CodeIgniter, freebie, and etc. Up to this step, the function and its page should be finished.

7. Add get_categories() function in Blog model.

function get_categories()
{
    $query = $this->db->get('entry_category');
    return $query->result();
}

This function will be called in your add new entry view to display a list of available categories.

8. Edit your add_new_entry function in Blog controller.

public function add_new_entry()
{
    if( ! $this->ion_auth->logged_in() && ! $this->ion_auth->is_admin() ) // block un-authorized access
    {
        show_404();
    }
    else
    {
        $data['title'] = 'Add new entry - '.$this->config->item('site_title', 'ion_auth');
        $data['categories'] = $this->blog_model->get_categories();

        $this->load->helper('form');
        $this->load->library(array('form_validation'));

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

        if ($this->form_validation->run() == FALSE)
        {
            //if not valid
            $this->load->view('admin/add_new_entry',$data);
        }
        else
        {
            //if valid
            $user = $this->ion_auth->user()->row();
            $title = $this->input->post('entry_name');
            $body = $this->input->post('entry_body');
            $categories = $this->input->post('entry_category');

            $this->blog_model->add_new_entry($user->id,$title,$body,$categories);
            $this->session->set_flashdata('message', '1 new post added!');
            redirect('add-new-entry');
        }
    }
}

Add a restriction to it. Only administrator can add a new entry. Don’t forget to call get_categories() so that we can list the categories.

9. Update add_new_entry.php file in views > admin.

<?php echo form_open('add-new-entry');?>
    <p><label>Title</label>
    <input type="text" name="entry_name" size="30" /></p>

    <h3>Category</h3>
    <p><?php if( isset($categories) && $categories): foreach($categories as $category): ?>
        <label><input class="checkbox" type="checkbox" name="entry_category[]" value="<?php echo $category->category_id;?>"><?php echo $category->category_name;?></label>
        <?php endforeach; else:?>
        Please add your category first!
        <?php endif; ?>
    </p>
    <p><label>Your Entry: (in html)</label>
    <textarea rows="16" cols="80%" name="entry_body" style="resize:none;"></textarea></p>

    <br />    

    <input class="button" type="submit" value="Submit"/>
    <input class="button" type="reset" value="Reset"/>    

</form>

The updated form of add new entry should be similar to the above code. Notice that I add a new input checkbox field name as entry_category in array because a post may have in several categories.

10. Do not forget to update add_new_entry() in the blog_model

Because I’m too lazy to put up the code here, I leave it to you guys on your preferences / way of your coding. You may see the way I code it in the source code if you downloaded it. So, do download the source code if you want to see it. 🙂

Since we are using ion_auth library, I also do some changes to the comment and entry table so that we can store information about the author of the entry and admins who logged in do not has to enter the name and email to reply comments.

If you are willing to retrieve the posts which categorised in a particular category, the following function works well. You may find it the blog model.

function get_category_post($slug)
{
    $list_post = array();

    $this->db->where('slug',$slug);
    $query = $this->db->get('entry_category'); // get category id
    if( $query->num_rows() == 0 )
        show_404();

    foreach($query->result() as $category)
    {
        $this->db->where('category_id',$category->category_id);
        $query = $this->db->get('entry_relationships'); // get posts id which related the category
        $posts = $query->result();
    }

    if( isset($posts) && $posts )
    {
        foreach($posts as $post)
        {
            $list_post = array_merge($list_post,$this->get_post($post->object_id)); // get posts and merge them into array
        }
    }
    return $list_post; // return an array of post object
}

What about update/delete posts and categories?

For a complete CRUD task for post and category, you may look the examples at active record class in CodeIgniter user guide page. NetTutsPlus also has some video tutorial on CRUD operations.

I think this is the last part for Creating a simple blog with CodeIgniter tutorial series. Don’t forget to download the source code for better understanding! Have questions? Do ask in comments!

P/s: This tutorial was written and published in Feb 2012.

4 Replies to “Create a simple blog using CodeIgniter 2 – Part 3”

  1. Hello,

    Your download link is not working
    “http://adf.ly/5ZyLv”

    Can you update the link

    1. Hello aquahunt

      The link works fine. You just need to wait the ads load and wait for five seconds.

      Then click skip ads to download.

      Or maybe you need to disable ads blocker plugins in your web browser to enable the download.

      Thanks.

Comments are closed.