Create a simple blog using CodeIgniter 2.0 – Part 1

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

CodeIgniter Logo

At the end of the tutorial, you should have a simple blog system with comment function. To download the complete sourcecode, scroll down to the end of this tutorial. You also may want to view the sample here. Just want to download and get lost from here? Click the link to download the files.

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:

--
-- Table structure for table `entry`
--

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 ;

--
-- Dumping data for table `entry`
--

2. Edit configuration.

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. You may refer to CodeIgniter for beginner for how to remove the index.php in url.

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 name 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!!! :D To be continued in part 2.

About

Pisyek Kumar is from Terengganu, Malaysia. A web developer extraordinaire, highly motivated on projects that involves utilization of his skills.

Tagged with: , ,
Posted in Blog, Framework, How to
43 comments on “Create a simple blog using CodeIgniter 2.0 – Part 1
  1. mahsyar says:

    nice one. haha rajin gila buat benda alah ni

  2. Mohd Isa says:

    [+] kalau wat testing site boleh ke? maksud aku untuk testing design coding like css, php, js or html. boleh ajar aku tak?

    [+] aku dah download, tp tak tau nak up cam mana…aku test kat wamp…cam mana nak setting database dan semua2?

    • Pisyek says:

      er, item no 1 aku x brape nak pasti, tapi item no dua tu senang aje, ko cari guide untuk create database dalam wamp. Pastu guna kod yang aku dah bagi kat atas skali tu. :D

  3. izzan says:

    Hi, i’m izzan from Indonesia, I accidentally found your site and read some stuff, especially your post about CI. Nice blog, :D

    heheheheh, btw i’m computer science student in department of computer science bogor agricultural university, final year ( hopely ); salam kenal ya dari saya, izzan…

    maybe we can share our knowledge in computer science, especially web development, :D

  4. fais says:

    Hello Mr.Pisyek,

    Here, i have some question and i really hope u can answer it.Currently i am learning this codeigniter too and i have tried your sample but it does not work.I use Xampp for the server,is it effect the coding inside ci?

    How to make it work?For your info, i use CodeIgniter v.1.7.2.

    Im looking forward to hearing from u about this matter.

    Thank You.

    • Pisyek says:

      FYI, any webserver is ok if it can run apache, php and mysql. Xampp, Wamp, Lamp, Mamp should be ok.

      It is clearly stated that this tutorial is meant for CI 2.0. There are some bit differences between CI 1.x and CI 2.0 in term of coding.

      My suggestion to you is please use the latest CI. (Now CI 2.0.2)

  5. syahzul says:

    bro, ade typo sikit kat blog controller:

    $this—>load->model(‘blog_model’);

    terlebih 2 dash.

    nice work btw.

  6. ladygirl says:

    Hi, I’ve gone through your tutorial.
    Tried it on my localhost. But i got an error.
    How should I actually put the url to view it on my browser ?
    Thank you. :)

    • Pisyek says:

      Can you give me the details on what error have you faced?

      Drop me an email with screenshots will be much easier for me to help you! :)

  7. coryladd says:

    I keep getting an error I wrote all of the pages just as you did here I checked all of my code with no luck.

    I get this error

    Parse error: syntax error, unexpected T_STRING, expecting ‘{‘ in /home/coryladd/public_html/application/models/blog_model.php on line 3

  8. mousesports says:

    Great, thanks.

    Slight mistake I believe: In the Blog Controller on line 30, I think you meant to write:
    ‘$this->load->view(‘blog/add_new_entry’);’ not ‘blog/add_new’.

  9. dunk says:

    hi,

    im a newb in this CI and really need ur guide for starter.

    I try to run your code by adding the new file in the CodeIgniter_2.0.2. I add all file in this folder:
    – controller\blog.php
    – model\blog_model.php
    – view\index.php
    – view\add_new_entry.php

    Can you explain to me what is this code mean?
    $this->load->view(‘blog/menu’);

    i don’t know y i cant run you code. am i doing it wrongly??

    thanks in advance

    • Pisyek says:

      Basically, the line is calling for html that contain code for menu. For me, it is easier to manage the layout if i seperate it accordingly such as header, footer, menu, etc. This is my style. :D

  10. nyobain says:

    is that possible to use admin login to create and edit post , allow or delete comment ? thanks

    • Pisyek says:

      Yes, it is possible. You can create user login for backend to manage posts and comments. I may write the tutorial, some day in future. :)

  11. nyobain says:

    thanks for quick answer, i’m new in code igniter, first i learn from nettuts, it’s 1.7.2 ver, some code didn’t worked, and now i read your code and learn it step by step, may i ask something if i got stucked ?
    thanks :)
    mantap lah panduannya

  12. nyobain says:

    i got

    404 Page Not Found

    The page you requested was not found.

    when try to open /new-post

    i follow your tutor, am i doing something wrong ?

    • Pisyek says:

      Please check your route.php file. You need to edit the file accordingly. Refer to the second part of this tutorial for details. :)

  13. nyobain says:

    it’s worked on localhost when i rename blog folder into blog2
    and that css, how to input it on ci ?
    one more question, how to change localhost/blog2 into localhost only
    thanks you helped me so much :)

    • Pisyek says:

      1. You have to check the config.php file
      2. See how i add css file in header view
      3. To do in localhost, all files and folders like application,system,index.php have to be put in htdocs/www folder.

  14. nyobain says:

    wow so quick, i got sick for 3 days, now i starting to learn again
    i see asset/css/style.css
    /www folder, is’t worked on cpanel hosting too ?
    http://www.nyobain.com/
    i put it in there
    now i realize something
    now i learn from your complete files in here – > ( Click the link to download the files.)
    many thanks :)

    • Pisyek says:

      Yes, it will work on hosting too!

      I see your css link is broken. If you’re following my folder structure, the css link will be like yourdomain.com/assets/css/file.css

  15. nyobain says:

    it’s not working, let me try to put all of them in 1 folder :)
    .
    .
    .
    .
    it’s worked on http://www.nyobain.com/blog
    after searching i find this one
    http://codeigniter.com/wiki/Automatic_configbase_url/
    thanks alot pisyek :)
    is that your name ?

  16. Ashar says:

    Hi

    Its a nice tutorial, direct and works. Just would like to inform that I believe you are calling menu.php from view. Perhaps you might want to mention to users to create the file.
    Secondly, in the controller under function add new entry line 30, I believe you would like to write ‘blog/add_new_entry’

    I am moving on to see the next tutorial.
    Its wonderful to see a site from someone in Malaysia. I grew up in Singapore before moving to Germany about 2 years. Now I hardly speak nor write any Malay. It is awesome to see people who are fluent still in the language. :)

    cheers
    Ashar

    (Dari yang jauh di Jerman :))

  17. Irul says:

    Hi, I’m irul from indonesia

    I’ve try your tutorial here, but i have a question.. how we access function add_new_entry?

    I’ve try to access this url “http://localhost/coba_ci/add_new_entry”
    but the result : “The requested URL /coba_ci/add_new_entry was not found on this server.”

    I hope you understand my question, my English is really bad.. hehe

    • Pisyek says:

      The coba_ci is a folder, isnt it?

      Maybe your actual url is localhost/coba_ci/blog/add_new_entry

      I have config in the route.php so that i can just ignore the blog controller and make url shorter.

      You have to config your route.php too. Please refer to the part 2 of this tutorial. :D

  18. Fadli Saad says:

    Hi Pisyek,

    Ada contoh utk buat dropdown select utk category e.g blog mesti ada category, so category stored dalam mysql, masa add ada option utk pilih which category.

    Thanks for the nice tutorial!
    Fadli Saad recently posted..Manage your server on AndroidMy Profile

  19. Fadli Saad says:

    Thanks, dah jumpa cara utk create dropdown from db, tinggal chained select je belum lagi :)
    Fadli Saad recently posted..Manage your server on AndroidMy Profile

  20. Nursultan says:

    may I ask somth from you:
    where we should locate view files, I’ve put them into views/blog/index.php is it right??
    after i tried to start it
    by address: localhost/blog
    it shows error:
    Error 404
    localhost
    12/19/11 13:31:35
    Apache/2.2.2 (Win32) DAV/2 mod_ssl/2.2.2 OpenSSL/0.9.8b mod_autoindex_color PHP/5.1.4

    Update: Sorry!!!! I found my mistake

  21. cilearner says:

    I tried your tutorial and download as well, at both…

    my base url is something like this

    localhost/codeignitor/blog2

    whenever i go to

    localhost/codeignitor/blog2/blog/add_new_entry.. i get an error

    The requested URL /codeignitor/blog2/blog/add_new_entry was not found on this server.

  22. Antonis says:

    Thank you , it’s working great.I’m trying to add some categories for the posts now.

2 Pings/Trackbacks for "Create a simple blog using CodeIgniter 2.0 – Part 1"
  1. [...] Create a simple blog using CodeIgniter 2.0 – Part 1 [...]

  2. [...] 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 sourcecode of this [...]

Questions?

Send your email to pisyek at gmail dot com.