How To Make A Blog In CodeIgniter!

How To Make A Blog In CodeIgniter!

September 21, 2017 Almost everyone up till now believed that blogs were to be made in WordPress. That's true. But, have you ever tried to make a blog in CodeIgniter Framework? Yes, it is definitely possible and easy too. If you are a beginner and want to make your blog in CodeIgniter, you can follow our steps and get your own blog up and running. Before starting the blog in CodeIgniter you need to make sure that CodeIgniter is already installed in your system. You can download it from their website. Set the URL, domain and database settings. You can take the help of guidelines available for setting up the database from the hosting providers. Now, let's get started with our quick steps: Create a Database: First of all you have to create a new database and give a name you want. We use three tables for storing and managing blog contents. Tables are names as: comments, posts and users. You can run below query in your phpmyadmin to creating the entire table with structure. Structure for table 'comments'
“CREATE TABLE `comments` (
  `comment_id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `post_id` int(11) NOT NULL,
  `comment` text NOT NULL,
  `date_added` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;”
Structure for table 'posts'
“CREATE TABLE `posts` (
  `post_id` int(11) NOT NULL,
  `post_title` varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
  `post` text CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
  `active` int(11) NOT NULL,
  `date_added` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `user_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;”
Structure for table 'users'
“CREATE TABLE `users` (
  `user_id` int(4) NOT NULL,
  `email` varchar(255) NOT NULL,
  `username` varchar(255) NOT NULL,
  `password` varchar(255) NOT NULL,
  `user_type` enum('admin','author','user') NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;”

Create Controller in application/controllers:

The second step is to create a file called users.php, blog.php, and comments.php in the controllers’ folder. You can write below given code: users.php
<?php
class Users extends CI_Controller
{
    public function __construct() {
        parent::__construct();
        $this->load->model('m_user');
    }
    function login()
    {
        if($this->session->userdata("user_id"))//If already logged in
        {
            redirect(base_url());//redirect to the blog page
        }
        $data['error'] = 0;
        if($this->input->post())//data inputed for login
        {
            $username = $this->input->post('username', TRUE);
            $password = $this->input->post('password', TRUE);
            $user_type = $this->input->post('user_type', TRUE);
            $user = $this->m_user->login($username, $password, $user_type);
            if(!$user){ $data['error'] = 1;}//when user doesn't exist
            else //when user exist
            {
                $this->session->set_userdata('user_id', $user['user_id']);
                $this->session->set_userdata('username', $user['username']);
                $this->session->set_userdata('user_type',$user['user_type']);
                redirect(base_url().'index.php/blog/');
            }
        }
        $class_name = array(
            'home_class'=>'', 
            'login_class' => 'current', 
            'register_class' => '',
            'upload_class'=>'',
            'contact_class'=>'');
        $this->load->view('header',$class_name);
        $this->load->view('v_login',$data);
        $this->load->view('footer');
    }
    function logout()
    {
        $this->session->sess_destroy();
        redirect(base_url().'index.php/blog/');
    }
    function register()
    {
        $data['error'] = NULL;
        if($this->input->post())
        {
            $config = array(
                array(
                    'field' => 'username',
                    'label' => 'Username',
                    'rules' => 'trim|required|min_length[3]|is_unique[users.username]'//is unique username in the user's table of DB
                ),
                array(
                    'field' => 'password',
                    'label' => 'Password',
                    'rules' => 'trim|required|min_length[5]|max_length[20]'
                ),
                array(
                    'field' => 'passconf',
                    'label' => 'Password confirmed',
                    'rules' => 'trim|required|matches[password]',
                ),
                array(
                    'field' => 'user_type',
                    'label' => 'User type',
                    'rules' => 'trim|required',
                ),
                array(
                    'field' => 'email',
                    'label' => 'Email',
                    'rules' => 'trim|required|is_unique[users.email]|valid_email',//is unique email in the user's table of DB
                ),
            );
            $this->load->library('form_validation');
            $this->form_validation->set_rules($config);
            if($this->form_validation->run() == FALSE)
            {
                $data['error'] = validation_errors();
            }
            else 
            {
                $data = array(
                    'username' => $this->input->post('username'),
                    'email' => $this->input->post('email'),
                    'password' => sha1($this->input->post('password')),
                    'user_type' => $this->input->post('user_type'),
                );
                $user_id = $this->m_user->create_user($data);
                $this->session->set_userdata('user_id',$user_id);
                $this->session->set_userdata('username',$this->input->post('username'));
                $this->session->set_userdata('user_type',$this->input->post('user_type'));
                redirect(base_url().'index.php/blog/');
            }
            
        }
        $class_name = array(
            'home_class'=>'', 
            'login_class' =>'', 
            'register_class' => 'current',
            'upload_class'=>'',
            'contact_class'=>'');
        
        $this->load->view('header',$class_name);
        $this->load->view('v_register',$data);
        $this->load->view('footer');
    }
}
?>
blog.php
<?php
class Blog extends CI_Controller {
    function __construct() {
        parent::__construct();
        $this->load->model('m_db');
    }

    function index($start = 0)//index page
    {
        $data['posts'] = $this->m_db->get_posts(5, $start);

        //pagination
        $this->load->library('pagination');
        $config['base_url'] = base_url() . 'index.php/blog/index/';//url to set pagination
        $config['total_rows'] = $this->m_db->get_post_count();
        $config['per_page'] = 5;
        $this->pagination->initialize($config);
        $data['pages'] = $this->pagination->create_links(); //Links of pages

        $class_name = array('home_class' => 'current', 'login_class' => '', 'register_class' => '', 'upload_class' => '', 'contact_class' => '');
        $this->load->view('header', $class_name);
        $this->load->view('v_home', $data);
        $this->load->view('footer');
    }

    function search($query = '')//index page
    {

        $query = $query != '' ? $query : $this->input->get('query', TRUE);

        $data['posts'] = $this->m_db->search_posts($query);

        //pagination
        $this->load->library('pagination');
        $config['base_url'] = base_url() . 'blog/search/?query=' . urlencode($query);//url to set pagination
        $config['total_rows'] = $this->m_db->get_post_count();
        $config['per_page'] = 5;
        $this->pagination->initialize($config);
        $data['pages'] = $this->pagination->create_links(); //Links of pages
        $data['query'] = $query; //Links of pages

        $class_name = array('home_class' => 'current', 'login_class' => '', 'register_class' => '', 'upload_class' => '', 'contact_class' => '');
        $this->load->view('header', $class_name);
        $this->load->view('v_search', $data);
        $this->load->view('footer');
    }

    function post($post_id)//single post page
    {
        $this->load->model('m_comment');
        $data['comments'] = $this->m_comment->get_comment($post_id);
        $data['post'] = $this->m_db->get_post($post_id);
        $class_name = ['home_class' => 'current', 'login_class' => '', 'register_class' => '', 'upload_class' => '', 'contact_class' => ''];
        $this->load->view('header', $class_name);
        $this->load->view('v_single_post', $data);
        $this->load->view('footer');
    }

    function new_post()//Creating new post page
    {
        //when the user is not an admin and author
        if (!$this->check_permissions('author'))
        {
            redirect(base_url() . 'index.php/users/login');
        }

        if ($this->input->post()) {
            
            $data = array('post_title' => $this->input->post('post_title'), 'post' => $this->input->post('post'), 'active' => 1,);
            $this->m_db->insert_post($data);
            redirect(base_url() . 'index.php/blog/');
        } else {

            $class_name = ['home_class' => 'current', 'login_class' => '', 'register_class' => '', 'upload_class' => '', 'contact_class' => ''];
            $this->load->view('header', $class_name);
            $this->load->view('v_new_post');
            $this->load->view('footer');
        }
    }

    function check_permissions($required)//checking current user's permission
    {
        $user_type = $this->session->userdata('user_type');//current user
        if ($required == 'user') {
            return isset($user);

        } elseif ($required == 'author') {
            return $user_type == 'author' || $user_type == 'admin';

        } elseif ($required == 'admin') {
            return $user_type == 'admin';
        }
    }

    function editpost($post_id)//Edit post page
    {
        if (!$this->check_permissions('author'))//when the user is not an admin and author
        {
            redirect(base_url() . 'index.php/users/login');
        }
        $data['success'] = 0;

        if ($this->input->post()) {
            $data = array('post_title' => $this->input->post('post_title'), 'post' => $this->input->post('post'), 'active' => 1);
            $this->m_db->update_post($post_id, $data);
            $data['success'] = 1;
        }
        $data['post'] = $this->m_db->get_post($post_id);

        $class_name = ['home_class' => 'current', 'login_class' => '', 'register_class' => '', 'upload_class' => '', 'contact_class' => ''];
        $this->load->view('header', $class_name);
        $this->load->view('v_edit_post', $data);
        $this->load->view('footer');
    }

    function deletepost($post_id)//delete post page
    {
        if (!$this->check_permissions('author'))//when the user is not an andmin and author
        {
            redirect(base_url() . 'index.php/users/login');
        }
        $this->m_db->delete_post($post_id);
        redirect(base_url() . 'index.php/blog/');
    }
}

?>
comments.php
<?php
class Comments extends CI_Controller
{
    function add_comment($postID)
    {
        if(!$this->input->post())
        {
            redirect(base_url().'index.php/blog/post'.$postID);
        }
        
        $user_type = $this->session->userdata('user_type');
        if(!$user_type)
        {
            redirect(base_url().'index.php/users/login');
        }
        
        $this->load->model('m_comment');
        $data = array(
            'post_id' => $postID,
            'user_id' => $this->session->userdata('user_id'),
            'comment' => $this->input->post('comment'),
        );
        $this->m_comment->add_comment($data);
        redirect(base_url().'index.php/blog/post/'.$postID);
    }
}

 ?> 

Create Models To Access Database Records:

Here we use some models to access database records. We create a function called “models” and write query inside the models function and use that model in our controller. Create a file called m_user.php, m_comment.php, and m_db.php in the models folder. m_user.php
<?php
class M_user extends CI_Model
{
    function create_user($data)
    {
        $this->db->insert('users', $data);
        return $this->db->insert_id();;
    }
    function login($username, $password, $user_type)
    {
        $match = array(
            'username'=>$username,
            'password' => sha1($password),
            'user_type' => $user_type
        );
        
        $this->db->select()->from('users')->where($match);
        $query = $this->db->get();
        return $query->first_row('array');
    }
    function get_emails()
    {
        $this->db->select('email');
        $this->db->from('users');
        $query = $this->db->get();
        return $query->result_array();
    }
}
?>
m_comment.php
<?php
class M_comment extends CI_Model
{
    function add_comment($data)
    {
        $this->db->insert('comments',$data);
        return $this->db->insert_id();
    }
    
    function get_comment($post_id)
    {
        $this->db->select('comments.*,users.username');
        $this->db->from('comments');
        $this->db->join('users','users.user_id = comments.user_id', 'left');
        $this->db->where('post_id',$post_id);
        $this->db->order_by('date_added','asc');
        $query = $this->db->get();
        return $query->result_array();
    }
}
 ?> 
m_db.php
<?php
class M_db extends CI_Model
{
    function get_posts($number = 10, $start = 0)
    {
        $this->db->select();
        $this->db->from('posts');
        $this->db->where('active',1);
        $this->db->order_by('date_added','desc');
        $this->db->limit($number, $start);
        $query = $this->db->get();
        return $query->result_array();
    }
	function search_posts($query)
	{
		$this->db->select();
		$this->db->from('posts');
		$this->db->like("post_title", $query, 'both');
		$this->db->or_like("post", $query, 'both');
		$this->db->order_by('date_added', 'desc');
		$query = $this->db->get();
		return $query->result_array();
	}
    function get_post_count()
    {
        $this->db->select()->from('posts')->where('active',1);
        $query = $this->db->get();
        return $query->num_rows;
    }
    function get_post($post_id)
    {
        $this->db->select();
        $this->db->from('posts');
        $this->db->where(array('active'=>1,'post_id'=>$post_id));
        $this->db->order_by('date_added','desc');
        $query = $this->db->get();
        return $query->first_row('array');
    }
    function insert_post($data)
    {
        $this->db->insert('posts',$data);
        return $this->db->insert_id();
    }
    
    function update_post($post_id, $data)
    {
        $this->db->where('post_id',$post_id);
        $this->db->update('posts',$data);
    }
    
    function delete_post($post_id)
    {
        $this->db->where('post_id',$post_id);
        $this->db->delete('posts');
    }
}
 ?> 

Create view Pages

Create view page inside application/views folders and load that view from controllers and pass the data that needed. v_new_post.php for creating new post:
<div id="site_content">
 <div id="content">
 <!-- insert the page content here -->
 <h1>New Post</h1>
 <form action="<?= base_url()?>index.php/blog/new_post/" method="post">
 <div class="form_settings">
 <p><span>Title</span><input class="" type="text" name="post_title" value="" /></p>
 <p><span>Description</span><textarea class="textarea" rows="15" cols="50" name="post"></textarea></p>
 <p style="padding-top: 15px"><span>&nbsp;</span><input class="submit" type="submit" name="add" value="Publish" /></p>
 </div>
 </form>
 </div>
</div>
v_home.php for listing all post:
<div id="site_content">

<?php include 'sidebar.php' ?>

<div id="content">

<?php if($this->session->userdata('user_id') && $this->session->userdata('user_type') != 'user')

{ ?>

<h2><a style="color: green" href="<?=  base_url()?>index.php/blog/new_post/"><span class="glyphicon glyphicon-pencil"></span> Create a new post</a></h2>

<?php } ?>

<!-- insert the page content here -->

<?php foreach($posts as $post)

{ ?>

<h2><a style="color:red;" href="<?=  base_url()?>index.php/blog/post/<?=$post['post_id']?>"><?=$post['post_title'];?></a></h2>

<?php if($this->session->userdata('user_id') && $this->session->userdata('user_type') != 'user')

{ ?>

<p>

<a href="<?=  base_url()?>index.php/blog/editpost/<?=$post['post_id']?>"><span class="glyphicon glyphicon-edit" title="Edit post"></span></a> |

<a href="<?=  base_url()?>index.php/blog/deletepost/<?=$post['post_id']?>"><span style="color:#f77;" class="glyphicon glyphicon-remove-circle" title="Delete post"></span></a>

</p>

<?php }?>

<p><?=  substr(strip_tags($post['post']), 0, 200).'...';?></p>

<p><a href="<?=  base_url()?>index.php/blog/post/<?=$post['post_id']?>">Read More</a></p>

<?php

}?>

<?=$pages?>

</div>

</div>
v_single_post.php to view single post and add comment.
<div id="site_content">

<div id="content">

<!-- insert the page content here -->

<?php if(!isset($post))
{
echo "This page was accessed incorrectly";
}

else //display the post
{
?>

<h2><?=$post['post_title']?></h2>

<p><?=$post['post']?></p>

 

<hr>

<h3>Comments</h3>

<?php       //if there is comments then print the comments

if(count($comments) > 0)
{

foreach ($comments as $row)
{
?>

<p><strong><?=$row['username']?></strong> said at <?= date('d-m-Y h:i A',strtotime($row['date_added']))?><br>

<?=$row['comment'];?></p><hr>

<?php   
}
}
else //when there is no comment
{
echo "<p>Currently, there are no comment.</p>";
}

if($this->session->userdata('user_id'))//if user is loged in, display comment box
{
?>

<form action="<?=  base_url()?>index.php/comments/add_comment/<?=$post['post_id']?>" method="post">

<div class="form_settings">

<p>

<span>Comment</span>

<textarea class="textarea" rows="8" cols="100" name="comment"></textarea>

</p>

<p style="padding-top: 15px">

<span>&nbsp;</span>

<input class="submit" type="submit" name="add" value="Add comment" />

</p>

</div>

</form>

<?php

}

else {//if no user is loged in, then show the loged in button

?>

<a href="<?=  base_url()?>index.php/users/login">Login to comment</a>

<?php   
}

}
?>

</div>
</div>
So, this was the simplest way we created a blog in CodeIgniter Framework. These however were just the requisite things.  

Related Posts

from my blog


How to get Weather Information in PHP

March 15, 2016

Would you like to implement functionality of Getting Weather Information in PHP? Try Below Code. <?php //Note: appid can be obtained after login on http://api.openweathermap.org $city="indore"; $country="in"; // By City...

Make Your Website More Effective and Responsive

February 22, 2015

In today's modern day, customers and readers are less interested in how your office looks and more interested in how well organized and updated your website is. The reason behind...

Top 5 Benefits of Embracing Responsive Web Development

December 10, 2014

Responsive Web Design (RWD) is basically defined as an approach of laying-out and coding a website in a way so that the final web interface can provide an optimal viewing...