Using Code Igniter to Enable Comments in a Blog Application

Welcome to the fourth episode of the series entitled “Building a Blogger with the Code Igniter PHP framework.” Comprised of seven approachable articles, this series steps you through the development of a blog application using this friendly – yet powerful — PHP framework. We include copious code samples to demonstrate how to use the MVC pattern to develop a real-world program.

Introduction

If you have followed the series this far, then you know that the real-world application we’re developing is a MySQL-driven blog application. Thanks to the Code Igniter PHP framework, we should be able to develop this application in a relatively short time, without having to spend long hours writing complex classes and functions.

Now that you have been introduced to the main goal of this series, it’s time to recapitulate what we covered in the last article. In that particular tutorial, I explained how to build a blog controller class that was charged with displaying on screen a bunch of blog entries, along with their corresponding comments, previously stored on a pair of MySQL tables.

In truth, this last process was performed in a pretty simplistic way, since I recreated a hypothetical scenario in which a few comments were already inserted into one of these MySQL tables. I hope that helped to demonstrate how the controller in question embedded this data into a view file for display purposes.

A decent blog application, however, must provide users with a mechanism that lets them post their comments easily, and the simplest way to do this is via an HTML form. Therefore, in the next few lines, I’ll be explaining how to modify the controller class and the comments view file created in the preceding article to incorporate a basic web form that permits users to post comments on a particular blog entry.

Now, it’s time to get rid of the preliminaries and see how to improve the functionality of this blog application by letting users to submit their own comments. Let’s jump in!

{mospagebreak title=The application so far}

Before I go straight to the point and show you how to incorporate into the blogger the ability to insert user comments into a MySQL table, first I’d like to list the two source files created in the previous article. They were actually the driving force of this web application. This way, you’ll get a good grasp of how these files looked before we modify them as I explained earlier. 

That being clarified, below are the respective definitions for the controller class and the view file that make the blogger work as expected. Here they are:


// definition for ‘blogger.php’ file (located at /system/application/controllers/ folder)


class Blogger extends Controller{

function Blogger(){

// load controller parent

parent::Controller();

// load database class and connect to MySQL

$this->load->database();

// load pagination library

$this->load->library(‘pagination’);

// load helper

$this->load->helper(‘url’);

}

// display all blog entries

function blogs(){

$data['title']=’Blog Entries Listing';

$data['result']=$this->db->get(‘blogs’,3,$this->uri->segment(3));

// set pagination parameters

$config['base_url']=’http://127.0.0.1/codeigniter/index.php/blogger/blogs/';

$config['total_rows']=$this->db->count_all(‘blogs’);

$config['per_page']=’3′;

$config['full_tag_open']='<div id="paginglinks">';

$config['full_tag_close']='</div>';

$this->pagination->initialize($config);

// create pagination links

$data['links']=$this->pagination->create_links();

// load ‘blogs_view’ view

$this->load->view(‘blogs_view’,$data);

}

// display all blog comments

function comments(){

$data['title']=’Blog Comments Listing';

$this->db->where(‘blog_id’,$this->uri->segment(3));

$data['result']=$this->db->get(‘blogs_comments’);

// load ‘blogs_comment_view’ view

$this->load->view(‘blogs_comment_view’,$data);

}

}



// definition for ‘blogs_view.php’ file (located at /system/application/views/ folder)


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

<title><?php echo $title;?></title>

</head>

<body>

<h1><?php echo $title;?></h1>

<?php foreach($result->result_array() as $blog):?>

<h2><?php echo $blog['title'];?></h2>

<p><?php echo $blog['text'];?></p>

<p><?php echo anchor(‘blogger/comments/’.$blog['id'],’View Blog Comments &gt;&gt;’);?></p>

<?php endforeach;?>

<?php echo $links;?>

</body>

</html>



// definition for ‘blogs_comment_view.php’ file (located at /system/application/views/ folder)


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

<title><?php echo $title;?></title>

</head>

<body>

<h1><?php echo $title;?></h1>

<?php if($result->num_rows()>0):?>

<?php foreach($result->result_array() as $comment):?>

<p><strong>Author: </strong><?php echo $comment['author'];?></p>

<p><strong>Comment:</strong></p>

<p><?php echo $comment['text'];?></p>

<p><?php echo anchor(‘blogger/blogs/’,’&lt;&lt; Back to blog’);?></p>

<?php endforeach;?>

<?php endif;?>

</body>

</html>


As you can see, the controller class is the module responsible for fetching all of the blog entries and their corresponding comments from the respective MySQL tables. The two additional views are tasked with displaying this data in the form of HTML pages.

Nevertheless, I have to admit that the blogger in its current state offers limited functionality, since it doesn’t provide users with a web form for posting their comments on a particular entry. To perform this operation, first it’s necessary to define a brand new method within the controller, and second, the signature of the "blogs_comments_view.php" file must be modified to include the online form.

It sounds like hard work, right? Not when using Code Igniter! In the section to come I’ll be showing you how to complete these tasks, so click on the link below and keep reading.

{mospagebreak title=Inserting comments with a Blogger controller class method}

As I expressed in the section that you just read, users will be able to submit several comments on a particular entry by way of a simple web form. As you may guess, this web page element needs to be coded into a view file, since it’s a part of the blogger’s visual presentation.

In order to insert these comments into the "blogs_comments" MySQL table, it’s necessary to define another method within the controller class that performs this task in a straightforward manner.

Below I listed the modified version of the controller in question. It incorporates a brand new method called "insert_comment()" that comes in useful for storing user-submitted posts on the corresponding MySQL table. Take a look at it, please:


class Blogger extends Controller{

function Blogger(){

// load controller parent

parent::Controller();

// load database class and connect to MySQL

$this->load->database();

// load pagination library

$this->load->library(‘pagination’);

// load helper

$this->load->helper(‘url’);

}

// display all blog entries

function blogs(){

$data['title']=’Blog Entries Listing';

$data['result']=$this->db->get(‘blogs’,3,$this->uri->segment(3));

// set pagination parameters

$config['base_url']=’http://127.0.0.1/codeigniter/index.php/blogger/blogs/';

$config['total_rows']=$this->db->count_all(‘blogs’);

$config['per_page']=’3′;

$config['full_tag_open']='<div id="paginglinks">';

$config['full_tag_close']='</div>';

$this->pagination->initialize($config);

// create pagination links

$data['links']=$this->pagination->create_links();

// load ‘blogs_view’ view

$this->load->view(‘blogs_view’,$data);

}

// display all blog comments

function comments(){

$data['title']=’Blog Comments Listing';

$this->db->where(‘blog_id’,$this->uri->segment(3));

$data['result']=$this->db->get(‘blogs_comments’);

// load ‘blogs_comment_view’ view

$this->load->view(‘blogs_comment_view’,$data);

}

// insert new blog comment

function insert_comment(){

$this->db->insert(‘blogs_comments’,$_POST);

redirect(‘blogger/comments/’.$_POST['blog_id']);

}

}


Despite its short signature, the above "insert_comment()" method is indeed quite useful. It inserts a new comment into the "blogs_comments" MySQL table, and then redirects the user to the comments web page when this insertion operation has been accomplished correctly.

As you can see, comments are collected via a POST HTML form, so in this case the $_POST PHP superglobal array is used for submitting this data to the respective database table.

Okay, at this stage the "Blogger" controller class has the ability to store new comments about different blog entries on a specific MySQL table. Nevertheless, this process would be rather incomplete if I didn’t show you how to code the web form that lets users to accomplish this task in a simple fashion.

Therefore, in the last section of this article I’ll be teaching you how to redefine the signature of the "blogs_comment_view.php" file to include the mentioned online form.

Please, jump forward and read the following segment.

{mospagebreak title=Redefining the blogs_comment_view.php file}

Coding a simple web form that permit users to post their comments on a particular blog entry is a no-brainer process that only requires you to modify the signature of the "blogs_comments_view.php" file that you saw before.

In this case, I’m going to use Code Igniter’s "form" helper function to dynamically generate the "action" attribute of the form, and also to create a hidden field that permits us to save the ID of the entry being commented.

If the previous explanation sounds rather confusing to you, then the following code sample should dissipate any possible doubts that you might still have:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

<title><?php echo $title;?></title>

</head>

<body>

<h1><?php echo $title;?></h1>

<?php if($result->num_rows()>0):?>

<?php foreach($result->result_array() as $comment):?>

<p><strong>Author: </strong><?php echo $comment['author'];?></p>

<p><strong>Comment:</strong></p>

<p><?php echo $comment['text'];?></p>

<p><?php echo anchor(‘blogger/blogs/’,’&lt;&lt; Back to blog’);?></p>

<?php endforeach;?>

<?php endif;?>

<?php echo form_open(‘blogger/insert_comment’);?>

<?php echo form_hidden(‘blog_id’,$this->uri->segment(3));?>

<p>Author:</p>

<p><input type="text" name="author" class="textbox" /></p>

<p>Enter your comments below:</p>

<p><textarea name="text" rows="10" cols="20"></textarea></p>

<p><input type="submit" value="Submit Comment" /></p>

</form>

</body>

</html>


Here you have it. Now the above view file includes a basic online form that allows users to submit their comments on a particular blog entry. In addition, it’s worthwhile to notice that the ID value of each entry is retrieved via the Code Igniter "uri" class, which is loaded automatically by its default controller.

And finally, here’s an additional screen capture that shows how this view file is rendered by the browser, after including into it the previous HTML form:



Before you proceed to read the conclusion of this article, don’t forget to save this modified version of the view to the Code Igniter /system/application/views/ folder, so it can be loaded by the pertaining controller class.

Assuming that you have saved the file, it’s time to test the improved blogger, right? Please point your browser to the following URL:


http://localhost/codeigniter/index.php/blogger/blogs/


Now, click on the link that takes you to the comments web page and simply use the online form to start posting new entries. If everything has been set up correctly, then you’ll be amazed how sweetly this blogger works.

Final thoughts

In this fourth episode of the series, I finished developing this simple blog application using Code Igniter. Logically, there’s plenty of room to introduce your own improvements and features to suit your personal needs; due to the program’s flexible structure, this should be a fairly painless process.

In the next part, I’ll be polishing the visual presentation of the blogger, since in its current state, it looks pretty primitive. So, now that you know what the upcoming article will be about, you can’t miss it!

[gp-comments width="770" linklove="off" ]

chat