Thursday, April 29, 2010

CodeIgniter comment system / shoutbox system tutorial/lesson.

Very simple and easy to use system on CodeIgniter. This can be further extended and integrated into your site as a shout box, chat system, comment system etc...
Easy to program and easy to use! great resource for people who are beginning with php and codeigniter .


So lets start.

Really simple, with hardly 25-30 lines of code in 3 files- thanks to CodeIgniter. If you are new to codeigniter please go through the CodeIgniter user guide, even if you don't its okay! i will brief you as we are programming.

Now, to get the feeling right, lets assume-
Your a geek, BIG TIME GEEK! and you have this website made on pure HTML and CSS. You get a good amount of traffic every month but then suddenly one night you feel that your site is lacking something... something is missing! You make your self a cup of coffee and your thinking ..and then it clicks to you! YOUR WEBSITE IS NOT INTERACTIVE! people cant interact with each other, they cant comment or chat... hmm too bad.
So you get your tool out(HEY! not that tool dude! put it back in PERVERT!), The 'geek' tool, GOOGLE! tak tak tak.. you type in - "comment system" or "chat system" and you REACH HERE. RELIEF! now your website can have some cool interactive features.
okay enough of my shit talks lets get started.

STEP 1- File structure

Codeigniter works on MVC model so open up your favorite text editor (i prefer notepad++ or NuSphere PhpED for codeigniter application development. code lobster is a good option too.) and open your application Model, View, Controller files.
<-- File structure of your codeigniter installation . I have changed the codeigniter folder name to shoutbox, Created a Model file 'shoutmodel.php', the View and Controller files are untouched and are the same that came with the codeigniter framework. View next post for step 2...

Leave a comment for help! 

STEP 2-CodeIgniter comment system / shoutbox system tutorial/lesson.

Step 2- Database
We need our website to be interactive and most interactive websites require a database.
We are working with codeigniter and php so our database will obviously be on MYSQL (hope you know SQL).
Lets create a database and call it 'shoutbox', obviously without ' ' .
Now create a table called 'shouts' with 4 fields for now,
  • The first field will be 'id', which will be a int with value 11 and have 'PRIMARY KEY' and 'AUTO INCREMENT' on.This is used for counting and arranging the shouts/comments/chats.
  • Second field will be 'name' with type 'varchar' and value 255.This is used to store the name of the person making a comment/shouting/chatting.
  • Third- 'shout' with type 'text'.This is where the comments/shouts/chats are stored
  • Forth- 'email' with type ' varchar' and value 255.Obviously to store the email.



You can create this table manually using phpmyadmin or using phpmysql sql option insert this code(copy paste the code below in red) and things will be auto created for you.
-- phpMyAdmin SQL Dump
-- version 3.2.4
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: Apr 29, 2010 at 09:43 AM
-- Server version: 5.0.90
-- PHP Version: 5.2.6

SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";

--
-- Database: zbyte_shoutbox`
--

-- --------------------------------------------------------

--
-- Table structure for table `shouts`
--

CREATE TABLE IF NOT EXISTS `shouts` (
`id` int(11) NOT NULL auto_increment,
`name` varchar(255) NOT NULL,
`shout` text NOT NULL,
`email` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=20 ;

--
-- Dumping data for table `shouts`
--

INSERT INTO `shouts` (`id`, `name`, `shout`, `email`) VALUES
(1, 'zeeshaan', 'first shout!', 'mail@fungupshup.com'),
(2, 'zeeshout', 'second shout', 'mail@zbyte.org'),
(3, 'greenday', 'Do you know your enemy', 'greenday@gd.com'),
(4, 'site-management', 'test4chk', 'works@gmail.com');

I have inserted some values there.. once you insert this code you will have something like this.

The first name is zeeshaan, Because my name is zeeshaan and the email is @fungupshup.com, cause that's one of my site .Second one is zeeshout, cause my pet name is zee and i shouted! and the email is @zbyte.org cause again that's one of my site. The third one is greenday cause i am a green day fan and the email is @gd.com cause thats the shortform for greenday and gd.com IS NOT MY SITE! just some general knowledge for you people :-D .okay you don't wana kill me for this!


Lets move on ...
Now, the database is ready we can go to step 3 ...

Leave a comment for help !

STEP 3-CodeIgniter comment system / shoutbox system tutorial/lesson.

STEP 3-
So we setup our database in step 2, now we will configure the database settings in CodeIgniter.
open the 'database.php' configuration file from system/application/config/ and all we have to edit is 4 lines-line number 40,41,42,43.
$db['default']['hostname'] = "localhost"; //mostly it is localhost so no need to change.
$db['default']['username'] = "root"; /*the username you set while creating your database. */
$db['default']['password'] = "root";//password you set for your database user.
$db['default']['database'] = "shoutbox";// the database name.
That's it. Your CodeIgniter database is now configured!

Head to Step 4...

Leave a comment for help !

STEP 4-CodeIgniter comment system / shoutbox system tutorial/lesson.

STEP 4-
The Real coding part.

Now that the files and database are ready lets move on to coding..
Lets start with the Model, we called our model 'shoutmodel.php' so now with the CodeIgniter conventions in mind we will create our model.

Obviously the model file will start and end with the php tags'' as its a php file, all our coding work goes inside these php tags.

Lets define our class-
we call our class Shoutmodel as the file name is shoutmodel.php.(I am not sure but i guess its a CodeIgniter convention to class the class name same as the file name with the first letter capital.)
That's what a basic CodeIgniter model looks like with a constructor. A constructor is a function with the function name same as the class name and is loaded automatically when the class is loaded unlike other functions.

Now we shall add our OWN FUNCTIONS to communicate with the database we created.
FIRST FUNCTION
We name our first function as 'getshout'.It will do just what it says, it will get shouts out of our database.


function getshout(){
$shouts = $this->db->get('shouts');
if($shouts->num_rows() > 0){foreach ($shouts->result() as $shout){
$data[] = $shout;
}
return $data;
}
}

The line '$shouts = $this->db->get('shouts');' is a ACTIVE RECORD STATEMENT which works same as the sql statement 'SELECT * FROM shouts', yes it will get all information from our database i.e -'shouts'.

The line 'if($shouts->num_rows() > 0)' Means that the code inside the if block {} will be run only if there are more than 0 or atleast one row OR shout/comment/chat in our database table.

'{foreach ($shouts->result() as $shout){$data[] = $shout;}' Lets break this into 2 parts -
  1. 'foreach ($shouts->result() as $shout)' this is the php foreach statement
  2. '{$data[] = $shout;}'This is the foreach code block. which defines a variable $data and the '[ ]'means its an array. so the whole thing '$data[] = $shout', stores $shout data, that is, as in the first line $shouts retrieves data from database using ACTIVERECORD and then in the Second lines first part '$shouts->result() as $shout' the result of $shouts is set as $shout. Then this $shout variable data is stored in the $data variable as an array. Its a little complex, hope you understood.

NOW ADDING OUR SECOND FUNCTION -
We call our second function 'newshout', and again it does what it says. it adds new shouts to our database
this ones pretty simple

function newshout(){
$name=$_POST["name"];//sets the variable $name to user input in the form input 'name' (form to be created in the VIEW file in STEP 6)

$shout=$_POST["shout"];//sets the variable $shout to user input in the form input 'shout' (form to be created in the VIEW file in STEP 6)

$email=$_POST["email"];//sets the variable $email to user input in the form input 'email' (form to be created in the VIEW file in STEP 6)

$ins_shout = array(
'name'=>$name,//associates the $name variable with the database table field 'name'
'shout'=>$shout,//associates the $shout variable with the database table field 'shout'
'email'=>$email //associates the $email variable with the database table field 'email'
);
$this->db->insert('shouts',$ins_shout);//ActiveRecord to insert the information gathered. The first parameter of insert is the table name and the second parameter is the data to be inserted, in our case it is in array form but it can be in object form too.[if you don't know what a parameter of a function is then- in insert('shouts',$ins_shout) , insert is the function and inside the ( ) are the parameters separated by commas.]
}




That should explain everything..

in case you want to directly copy paste, here's the code again without comments


class Shoutmodel extends Model{
/*constructor function*/
function Shoutmodel(){
parent::Model();
}

function getshout(){
$shouts = $this->db->get('shouts');
if($shouts->num_rows() > 0){foreach ($shouts->result() as $shout){
$data[] = $shout;
}
return $data;
}
}


function newshout(){
$name=$_POST["name"];
$shout=$_POST["shout"];
$email=$_POST["email"];
$ins_shout = array(
'name'=>$name,
'shout'=>$shout,
'email'=>$email
);
$this->db->insert('shouts',$ins_shout);
}
}
?>


Well that's all for our Model file.. lets move to Step 5...


Leave a comment for help !

STEP 5-CodeIgniter comment system / shoutbox system tutorial/lesson.

STEP 5-
The Controller.

Now that we have our Files, Database and Model ready, lets get to the controller, where the REAL action takes place. Model --> <--Controller --> View! That's how it works!

There is already a controller that came with the CodeIgniter installation, 'welcome.php', we will stick to that but remove everything inside that file except the lines - '
class Welcome extends Controller {
}'

Lets start with our functions. This time again we just have 2 functions
  1. Index function , this is the default controller function in CodeIgniter.If you load your controller using URI eg:localhost/codeigniter/index.php/welcome , the index function is loaded unless you specify your function in the URI eg:localhost/codeigniter/index.php/welcome/functionname.Here's our index function-

    function index()
    {
    $this->load->Model('shoutmodel');//loading the model
    $data['shout']=$this->shoutmodel->getshout();//loading the model function 'getshout()' and storing the 'getshout' function data as array in $data variable
    $this->load->view('index',$data); //loading the view 'index.php' and sending stored data in $data variable to view
    }
    That's explains all.


  2. function shout()
    {
    $this->load->Model('shoutmodel');//loading the model
    $this->shoutmodel->newshout();//loading the model function 'newshout()'
    $data['shout']=$this->shoutmodel->getshout();//loading the model function 'getshout()' and storing the 'getshout' function data as array in $data variable
    $this->load->view('index',$data) ;//loading the view 'index.php' and sending stored data in $data variable to view
    }
The controller file without comments

class Welcome extends Controller {

function index()
{
$this->load->Model('shoutmodel');
$data['shout']=$this->shoutmodel->getshout();
$this->load->view('index',$data);
}

/*function index()
{

}*/

function shout()
{
$this->load->Model('shoutmodel');
$this->shoutmodel->newshout();
$data['shout']=$this->shoutmodel->getshout();
$this->load->view('index',$data) ;
}
}

i know its getting a little boring ... but guess what, its almost done!
TOWARDS THE LAST STEP...

Leave a comment for help !

STEP 6-CodeIgniter comment system / shoutbox system tutorial/lesson.

STEP 6-
THE VIEW.

This tutorial is assuming that you know good amount of HTML, CSS and basics of PHP, so this should be the easiest step.


<html>

<head>

<title>Welcome to CodeIgniter shoutbox!</title>



<style type="text/css">



body {

background-color: #fff;

margin: 40px;

font-family: Lucida Grande, Verdana, Sans-serif;

font-size: 14px;

color: #4F5155;

}



a {

color: #003399;

background-color: transparent;

font-weight: normal;

}



h1 {

color: #444;

background-color: transparent;

border-bottom: 1px solid #D0D0D0;

font-size: 16px;

font-weight: bold;

margin: 24px 0 2px 0;

padding: 5px 0 6px 0;

}



code {

font-family: Monaco, Verdana, Sans-serif;

font-size: 12px;

background-color: #f9f9f9;

border: 1px solid #D0D0D0;

color: #002166;

display: block;

margin: 14px 0 14px 0;

padding: 12px 10px 12px 10px;

}



</style>

</head>

<body>



<h1>Welcome to Shout Box!</h1>



<p>Recent shouts</p>





<?php foreach($shout as $shout): ?>



<code> <b><?php echo $shout->name.' says -';?></b><br><?php echo $shout->shout?></code>

<?php endforeach; ?>



<p>The corresponding controller for this page is found at:</p>

<code>system/application/controllers/welcome.php</code>



<p><b>Submit your own SHOUT!!</b></p>

<form action="http://localhost/shoutbox/index.php/welcome/shout" method="post">

<fieldset>

<legend>ShoutInfo:</legend>

Name:<input type="text" name="name" />

What to Shout?:<input type="text" name="shout" />

Email:<input type="text" name="email" />

<input type="submit" value="submit" name="submit" />



</fieldset>

</form>



<p><br />Page rendered in {elapsed_time} seconds</p>



</body>

</html>

I hope that's easy to understand.. if not please leave a comment and i will explain it!
Thank you!.

Leave a comment for help !