How to create a simple blog using codeigniter and MySQL

In this article I will explain you how to create a simple blog using codeigniter and MySQL. First you need to install codeigniter and do some basic setting. For installation guide read this tutorial Codeigniter installation beginner guide.
Once you are done with the installation create a database for your blog and create two table in one table we will save the category and in the second table we will save the POST of the category.

CREATE TABLE IF NOT EXISTS `Article` (
`Id` int(50) NOT NULL AUTO_INCREMENT,
`Category_id` int(50) NOT NULL,
`Title` varchar(255) NOT NULL,
`Description` text NOT NULL,
`DateTime` datetime NOT NULL,
`FeatureImage` varchar(200) NOT NULL,
PRIMARY KEY (`Id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=8 ;

CREATE TABLE IF NOT EXISTS `Category` (
`Id` int(50) NOT NULL AUTO_INCREMENT,
`Type` varchar(255) NOT NULL,
`Description` text NOT NULL,
`CreatedDate` datetime NOT NULL,
PRIMARY KEY (`Id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=22 ;

CREATE TABLE IF NOT EXISTS `UploadedFile` (
`id` int(50) NOT NULL AUTO_INCREMENT,
`CategoryId` int(50) NOT NULL,
`ArticleId` int(50) NOT NULL,
`DateTimeSaved` datetime NOT NULL,
`FileName` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=7 ;

Next, configure database connectivity in application/config/database.php:

$db['default']['hostname'] = "localhost";
$db['default']['username'] = "root";
$db['default']['password'] = "secret";
$db['default']['database'] = "blog";
$db['default']['dbdriver'] = "mysql";

Next, our application will have a single controller named blog, so let’s go ahead and set the default controller to ‘blog’ in application/config/routes.php:

$route['default_controller'] = "blog";

Now create the view files inside the view folder to insert, edit, update and show your category and post. Below are the files copy and paste the code respective to all files. I am not using CSS in the view files. This article is just to understand the basics of how to create a blog app.

addCategory.php

<ul class="treeview-menu">
<li><a href="<?php echo site_url('Blog/addCategory');?>"><i class="fa fa-angle-double-right"></i> Add Category</a></li>
<li><a href="<?php echo site_url('Blog/allCategory');?>"><i class="fa fa-angle-double-right"></i> View All Categories</a></li>
<li><a href="<?php echo site_url('Blog/addArticle');?>"><i class="fa fa-angle-double-right"></i> Add Article</a></li>
<li><a href="<?php echo site_url('Blog/allArticle');?>"><i class="fa fa-angle-double-right"></i> All Article</a></li>
</ul>
<form role="form" method = "POST" action = "<?php echo site_url('Blog/addCategory');?>">
<div class="box-body">
<div class="form-group">
<label for="exampleInputEmail1">Title</label><br>
<input type="text" name = "title" class="form-control" id="exampleInputEmail1" placeholder="">
</div>
<div>
<label>Description</label><br>
<textarea class="form-control" rows="10" name="desc" placeholder="Enter ..."></textarea>
</div>
</div>
<!-- /.box-body -->
<div class="box-footer">
<button type="submit" name = "addCategory" class="btn btn-primary">Submit</button>
</div>
</form>
<?php if(!empty($msg)){ echo $msg;};?>

allCategory.php

<ul class="treeview-menu">
<li><a href="<?php echo site_url('Blog/addCategory');?>"><i class="fa fa-angle-double-right"></i> Add Category</a></li>
<li><a href="<?php echo site_url('Blog/allCategory');?>"><i class="fa fa-angle-double-right"></i> View All Categories</a></li>
<li><a href="<?php echo site_url('Blog/addArticle');?>"><i class="fa fa-angle-double-right"></i> Add Article</a></li>
<li><a href="<?php echo site_url('Blog/allArticle');?>"><i class="fa fa-angle-double-right"></i> All Article</a></li>
</ul>
<table id="example1" class="table table-bordered table-striped">
<thead>
<tr>
<th>Title</th>
<th>Description</th>
<th>Published On</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php foreach($Category as $row) { ?>
<tr>
<td><?php echo $row->Type;?></td>
<td><?php echo $row->Description;?></td>
<td><?php echo $row->CreatedDate;?></td>
<td><a href="<?php echo site_url('Blog/editCategory');?>/<?php echo $row->Id;?>">Edit</a>
<a href="<?php echo site_url('Blog/deleteCategory');?>/<?php echo $row->Id;?>">Delete</a></td>
</tr>
<?php } ?>
</tbody>
</table>

addArticle.php

<ul class="treeview-menu">
<li><a href="<?php echo site_url('Blog/addCategory');?>"><i class="fa fa-angle-double-right"></i> Add Category</a></li>
<li><a href="<?php echo site_url('Blog/allCategory');?>"><i class="fa fa-angle-double-right"></i> View All Categories</a></li>
<li><a href="<?php echo site_url('Blog/addArticle');?>"><i class="fa fa-angle-double-right"></i> Add Article</a></li>
<li><a href="<?php echo site_url('Blog/allArticle');?>"><i class="fa fa-angle-double-right"></i> All Article</a></li>
</ul>
<!-- Right side column. Contains the navbar and content of the page -->
<aside class="right-side">
<!-- Content Header (Page header) -->
<section class="content-header">
<h1>
Add New Article
</h1>
</section>
<!-- Main content -->
<section class="content">
<div class='row'>
<div class='col-md-12'>
<div class='box box-info'>
<div class="box-body">
<form method = "POST" action = "<?php echo site_url('Blog/addArticle');?>" enctype='multipart/form-data'>
<div class="form-group">
<label for="exampleInputEmail1">Title</label>
<input type="text" name = "title" class="form-control" id="exampleInputEmail1" placeholder="">
</div>
<div class="form-group">
<label> Select Category</label>
<select class="form-control" name="category">
<option>Select</option>
<?php  foreach($category as $row){?>
<option value = "<?php echo $row->Id;?>"><?php echo $row->Type;?></option>
<?php } ?>
</select>
</div>
<div class='box-header'>
<h3 class='box-title'>Description</h3>
<!-- tools box -->
<div class="pull-right box-tools">
<button class="btn btn-info btn-sm" data-widget='collapse' data-toggle="tooltip" title="Collapse"><i class="fa fa-minus"></i></button>
<button class="btn btn-info btn-sm" data-widget='remove' data-toggle="tooltip" title="Remove"><i class="fa fa-times"></i></button>
</div>
<!-- /. tools -->
</div>
<!-- /.box-header -->
<div class='box-body pad'>
<textarea id="editor1" name="editor1" rows="10" cols="80">
</textarea>
</div>
<div class="form-group">
<label for="exampleInputFile">Add Feature Image</label>
<input type="file" name="featureImage" id="exampleInputFile">
</div>
<div class="form-group">
<label for="exampleInputFile">Upload more Images</label>
<input type="file" name="userfile[]" id="exampleInputFile" multiple>
</div>
<div class="box-footer">
<button type="submit" name="addArticle" class="btn btn-primary">Submit</button>
</div>
</form>
</div>
<!-- /.box -->
</div>
<!-- /.col-->
</div>
<!-- ./row -->
</section>
<!-- /.content -->
</aside>
<!-- /.right-side -->
</div><!-- ./wrapper -->
<!-- jQuery 2.0.2 -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<!-- Bootstrap -->
<script src="<?php echo base_url('assets/js/bootstrap.min.js');?>" type="text/javascript"></script>
<!-- BlogLTE App -->
<script src="<?php echo base_url('assets/js/BlogLTE/app.js');?>" type="text/javascript"></script>
<!-- CK Editor -->
<script src="<?php echo base_url('assets/js/plugins/ckeditor/ckeditor.js');?>" type="text/javascript"></script>
<!-- Bootstrap WYSIHTML5 -->
<script src="../../js/plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
// Replace the <textarea id="editor1"> with a CKEditor
// instance, using default configuration.
CKEDITOR.replace('editor1');
//bootstrap WYSIHTML5 - text editor
$(".textarea").wysihtml5();
});
</script>

allArticle.php

<ul class="treeview-menu">
<li><a href="<?php echo site_url('Blog/addCategory');?>"><i class="fa fa-angle-double-right"></i> Add Category</a></li>
<li><a href="<?php echo site_url('Blog/allCategory');?>"><i class="fa fa-angle-double-right"></i> View All Categories</a></li>
<li><a href="<?php echo site_url('Blog/addArticle');?>"><i class="fa fa-angle-double-right"></i> Add Article</a></li>
<li><a href="<?php echo site_url('Blog/allArticle');?>"><i class="fa fa-angle-double-right"></i> All Article</a></li>
</ul>
<table id="example1" class="table table-bordered table-striped">
<thead>
<tr>
<th>Title</th>
<th>Description</th>
<th>Published On</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php foreach($Article as $row) { ?>
<tr>
<td><a href = "<?php echo site_url('Blog/editArticle');?>/<?php echo $row->Id;?>"><?php echo $row->Title;?></a></td>
<td><?php echo $row->Description;?></td>
<td><?php echo $row->DateTime;?></td>
<td><a href="<?php echo site_url('Blog/editArticle');?>/<?php echo $row->Id;?>">Edit</a>
<a href="<?php echo site_url('Blog/deleteArticle');?>/<?php echo $row->Id;?>">Delete</a></td>
</tr>
<?php } ?>
</tbody>
</table>

editArticle.php

<ul class="treeview-menu">
<li><a href="<?php echo site_url('Blog/addCategory');?>"><i class="fa fa-angle-double-right"></i> Add Category</a></li>
<li><a href="<?php echo site_url('Blog/allCategory');?>"><i class="fa fa-angle-double-right"></i> View All Categories</a></li>
<li><a href="<?php echo site_url('Blog/addArticle');?>"><i class="fa fa-angle-double-right"></i> Add Article</a></li>
<li><a href="<?php echo site_url('Blog/allArticle');?>"><i class="fa fa-angle-double-right"></i> All Article</a></li>
</ul>
<form method = "POST" action = "<?php echo site_url('Blog/updateArticle');?>" enctype='multipart/form-data'>
<div class="form-group">
<label for="exampleInputEmail1">Title</label>
<input type="text" name = "title" class="form-control" id="exampleInputEmail1" placeholder="" value = "<?php echo $getArticleById['0']->Title;?>">
</div>
<div class="form-group">
<label> Select Category</label>
<select class="form-control" name="category">
<option value = "<?php echo $getArticleById[0]->c_id;?>"><?php echo $getArticleById['0']->Type;?></option>
<?php  foreach($category as $row){?>
<option value = "<?php echo $row->Id;?>"><?php echo $row->Type;?></option>
<?php } ?>
</select>
</div>
<div class='box-header'>
<h3 class='box-title'>Description</h3>
<!-- tools box -->
<div class="pull-right box-tools">
<button class="btn btn-info btn-sm" data-widget='collapse' data-toggle="tooltip" title="Collapse"><i class="fa fa-minus"></i></button>
<button class="btn btn-info btn-sm" data-widget='remove' data-toggle="tooltip" title="Remove"><i class="fa fa-times"></i></button>
</div>
<!-- /. tools -->
</div>
<!-- /.box-header -->
<div class='box-body pad'>
<textarea id="editor1" name="editor1" rows="10" cols="80">
<?php echo $getArticleById['0']->Description;?>
</textarea>
</div>
<div class="form-group">
<label for="exampleInputFile">Add Feature Image</label>
<input type="file" name="featureImage" id="exampleInputFile">
</div>
<div class="form-group">
<label for="exampleInputFile">Upload more Images</label>
<input type="file" name="userfile[]" id="exampleInputFile" multiple>
</div>
<div class="box-footer">
<button type="submit" name="addArticle" class="btn btn-primary">Submit</button>
</div>
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<!-- Bootstrap -->
<script src="<?php echo base_url('assets/js/bootstrap.min.js');?>" type="text/javascript"></script>
<!-- BlogLTE App -->
<script src="<?php echo base_url('assets/js/BlogLTE/app.js');?>" type="text/javascript"></script>
<!-- CK Editor -->
<script src="<?php echo base_url('assets/js/plugins/ckeditor/ckeditor.js');?>" type="text/javascript"></script>
<!-- Bootstrap WYSIHTML5 -->
<script src="../../js/plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
// Replace the <textarea id="editor1"> with a CKEditor
// instance, using default configuration.
CKEDITOR.replace('editor1');
//bootstrap WYSIHTML5 - text editor
$(".textarea").wysihtml5();
});
</script>

editCategory.php

<ul class="treeview-menu">
<li><a href="<?php echo site_url('Blog/addCategory');?>"><i class="fa fa-angle-double-right"></i> Add Category</a></li>
<li><a href="<?php echo site_url('Blog/allCategory');?>"><i class="fa fa-angle-double-right"></i> View All Categories</a></li>
<li><a href="<?php echo site_url('Blog/addArticle');?>"><i class="fa fa-angle-double-right"></i> Add Article</a></li>
<li><a href="<?php echo site_url('Blog/allArticle');?>"><i class="fa fa-angle-double-right"></i> All Article</a></li>
</ul>
<form role="form" method = "POST" action = "<?php echo site_url('Blog/updateCategory');?>">
<div class="box-body">
<div class="form-group">
<label for="exampleInputEmail1">Title</label>
<input type="text" name = "title" class="form-control" id="exampleInputEmail1" placeholder="" value= "<?php echo $getCategoryById['0']->Type;?>">
</div>
<div>
<label>Description</label>
<textarea class="form-control" rows="3" name="desc" placeholder="Enter ...">
<?php echo $getCategoryById['0']->Description;?></textarea>
</div>
</div><!-- /.box-body -->
<div class="box-footer">
<button type="submit" name = "addCategory" class="btn btn-primary">Submit</button>
</div>
</form>
<?php if(!empty($msg)){ echo $msg;};?>

Once you are done with your view file creation open the controller and create a controller name Blog.php (make sure first latter of the file name capital).  We will use controller to show the view and call model to insert and select data from the database. Copy and paste the below code in the file

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/**
* User class.
*
* @extends CI_Controller
*/
class Blog extends CI_Controller {
/**
* __construct function.
*
* @access public
* @return void
*/
public function __construct() {
parent::__construct();
$this->load->library(array('session'));
$this->load->helper(array('url'));
$this->load->helper('cookie');
$this->load->model('Blog_model');
}
public function index() {
$this->load->view('addCategory');
}
public function addCategory() {
if(isset($_POST['addCategory']))
{
$data = array('Type'=>$this->input->post('title'),
'Description'=>$this->input->post('desc'),
'CreatedDate'=>date('Y-m-d h:i:s')
);
$this->db->insert('Category',$data);
$data['msg'] = "Category inserted Successfully";
}
$data['error'] = '';
$this->load->view('addCategory',$data);
}
public function addArticle() {
if(isset($_POST['
addArticle']))
{
if (isset($_FILES['userfile']))
{
//echo "hello";die;
$this->load->library('upload');
$files = $_FILES;
$cpt = count($_FILES['userfile']['name']);
for($i=0; $i<$cpt; $i++)
{
$_FILES['userfile']['name']= str_replace(' ', '-',$files['userfile']['name'][$i]);
$_FILES['userfile']['type']= $files['userfile']['type'][$i];
$_FILES['userfile']['tmp_name']= $files['userfile']['tmp_name'][$i];
$_FILES['userfile']['error']= $files['userfile']['error'][$i];
$_FILES['userfile']['size']= $files['userfile']['size'][$i];
$this->upload->initialize($this->set_upload_options());
$this->upload->do_upload();
$fileName = str_replace(' ', '-',$_FILES['userfile']['name']);
$images[] = $fileName;
}
$fileName = implode(',',$images);
$task = $this->Blog_model->addArticle($fileName);
}else{
$filename='';
$task = $this->Blog_model->addArticle($filename);
}
}
$data['category'] = $this->Blog_model->allCategory();
$this->load->view('addArticle',$data);
}
private function set_upload_options()
{
//  upload an image options
$config = array();
$config['upload_path'] = './upload/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size']      = '0';
$config['overwrite']     = FALSE;
return $config;
}
public function allCategory()
{
$this->db->select('*');
$this->db->from('Category');
$data['Category'] = $this->db->get()->result();
$this->load->view('allCategory',$data);
}
public function allArticle()
{
$this->db->select('*');
$this->db->from('Article');
$data['Article'] = $this->db->get()->result();
$this->load->view('allArticle',$data);
}
public function editArticle($id)
{
$this->db->select('*');
$this->db->from('Article');
$data['Article'] = $this->db->get()->result();
$data['category'] = $this->Blog_model->allCategory();
$data['getArticleById'] = $this->Blog_model->getArticleById($id);
$data['main_content'] = 'editArticle';
$this->load->view('editArticle',$data);
}
public function deleteArticle($id)
{
$this->db->where('Id',$id);
$this->db->delete('Article');
$this->db->select('*');
$this->db->from('Article');
$data['Article'] = $this->db->get()->result();
$this->load->view('allArticle',$data);
}
public function editCategory($id)
{
$data['getCategoryById'] = $this->Blog_model->getCategoryById($id);
$this->load->view('editCategory',$data);
}
public function deleteCategory($id)
{
$this->db->where('Id',$id);
$this->db->delete('Article');
$this->db->select('*');
$this->db->from('Category');
$data['Category'] = $this->db->get()->result();
$this->load->view('allCategory',$data);
}
}

Now create a file name Blog_model.php inside the folder model and copy and paste the below code.

<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class Blog_model extends CI_Model {
public function __construct() {
parent::__construct();
$this->load->database();
}
public function addArticle($fileName)
{
$data = array('Title'=>$this->input->post('title'),
'Category_id'=>$this->input->post('category'),
'Description'=>$this->input->post('editor1'),
'DateTime'=>date('Y-m-d h:i:s'),
'FeatureImage'=>$_FILES['userfile']['name']
);
$this->db->insert('Article',$data);
$articleId = $this->db->insert_id();
if($fileName!='' ){
$filename1 = explode(',',$fileName);
foreach($filename1 as $file){
$file_data = array(
'FileName' => $file,
'DateTimeSaved' => date('Y-m-d h:i:s'),
'ArticleId' => $articleId,
'CategoryId' => $this->input->post('category')
);
$this->db->insert('UploadedFile', $file_data);
}
}
}
public function allCategory()
{
$this->db->select('*');
$this->db->from('Category');
return  $this->db->get()->result();
}
public function getArticleById($id)
{
$this->db->select('Article.*,Category.Type as Type,Category.Id as c_id,');
$this->db->from('Article');
$this->db->join('Category','Category.Id = Article.Category_id');
$this->db->where('Article.Id',$id);
return  $this->db->get()->result();
}
public function getCategoryById($id)
{
$this->db->select('*');
$this->db->from('Category');
$this->db->where('Id',$id);
return  $this->db->get()->result();
}
}

Now run the URL http://localhost/codeigniter/. Your web-browser will look like below

blog application using codeigniter

You will be able to add the category and article for your blog. Make sure first you create the category then create the article or post for that category.

Hope this article how to create a simple blog using codeigniter and MySQL will help you to build a simple blog application where you will be able to insert, edit, delete and update the article and category and you can upload the multiple files and feature image for the article.

  • rajiv

    addArticle is not working , i have added the categories but in addArticle data is not geeting saved in database