Pages

Basic PHP Crash Course (part 3)

Thursday, March 29, 2012
This post is part 3 of the Basic PHP Crash Course. If you have never red before this Crash Course, you should read part 1 and part 2 first. Before enhancing our site, I want to explain you about the function.

What is a function?

A function is a block of code that has a name. It is not executed when we load the page. We need to call its name when we need to execute that block of code. And then we can call any time whenever we need it. If you have some code that need to use many time, you should use as the function. The function name can start with a letter or underscore (not a number) To understand the idea of function, we need to create our own simple function.

Simple Function

Let's start with the hello world function.
<?php
  function hello()
  {
   echo "Hello World!";
  }
hello();
?>

Function with parameter

Parameter is a variable that we send to our function to use withing our function.
<?php
  function hello($name)
  {
   echo "Hello ".$name;
  }
hello("Jack");
?>

Function with return value

Return value is a variable that return from our function. Sometime we need a return value
<?php
function add($a,$b)
{
 $result = $a + $b;
 return $result;
}
$total = add(5,3);
echo $total;
echo add(3,5);
?>
We can use the return value like above example and like int our web site.

Enhancing our site

There is no need to change in our index.php. For our process.php, we need to test whether the user fill the form data or not. To determine whether a variable is set, we will use isset() function. In PHP, there are many built-in functions. I create a tutorial about this here. Following is our new process.php
<html>
<head>
 <title>Order Process</title>
</head>
<body>
<?php
if($_POST['submit']=='Submit Order')
{
 if( isset($_POST['cus_name']) && isset($_POST['quantity']) && isset($_POST['address']) )
 {
  $cus_name = $_POST['cus_name'];
  $quantity = $_POST['quantity'];
  $address = $_POST['address'];
 ?>
 <p>Thank <?php echo $cus_name; ?> !</p>
 <p>You order <?php echo $quantity; ?> pizza.</p>
 <?php
  $total = $quantity * 10;
 ?>
 <p>It will cost you <?php echo $total; ?> $.</p>
 <p>We will send withing 2 hours to <?php echo $address; ?>.</p>
 <?php
    } 
 else
  echo "You need to fill all data";
 ?> 
 <?php } ?>
</body>
</html>

Explanation

Let's talk about isset() function. We will pass at least one parameter and it will return boolean true or false. It will return TRUE if var exists; FALSE otherwise.

Logical Operators

If you need to combine the results of logical conditions, you must be use logical operators. Following table is PHP logical operators.
!NOT
&&AND
||OR
andAND
orOR
xorXOR
Read more ...

Basic PHP Crash Course (part 2)

Sunday, March 25, 2012
This post is part 2 of the Basic PHP Crash Course. In part 1, we discuss about the html form, php variable, post method and some operator. In this part, we will discuss about php if() statement and comparison operators by enhancing our pizza shop site.

We created two file index.php and process.php in part 1.
There is no need to change in our index.php.

For our process.php,
we should know whether the form is submitted or not before we process the form. If the user run this url "http://localhost/pizza_shop/process.php" directly, user can get error.
So we have to change in our process.php. Our new process.php is as follow.


<html>
<head>
 <title>Order Process</title>
</head>
<body>
 <?php
 if($_POST['submit']=='Submit Order')
 {
  $cus_name = $_POST['cus_name'];
  $quantity = $_POST['quantity'];
  $address = $_POST['address'];
 ?>
 <p>Thank <?php echo $cus_name; ?> !</p>
 <p>You order <?php echo $quantity; ?> pizza.</p>
 <?php
  $total = $quantity * 10;
 ?>
 <p>It will cost you <?php echo $total; ?> $.</p>
 <p>We will send withing 2 hours to <?php echo $address; ?>.</p>
 <?php } ?>
</body>
</html>

Explanation

Sometime we need to do some action depend on other condition. For this saturation we will use if statement. Below is the idea of the "if" conditional statement.

if

if (this condition is true)
this action will be execute

if...else

if (condition one is true)
action one will be execute
else
action two will be execute

if...elseif...else

if (condition one is true)
action one will be execute
elseif (condition two is true)
action two will be execute
.
.
.
else
last action will be execute

Examples

Below is syntax of the "if" conditional statements.

if


<?php
 $a = 5;
 $b = 3;
 if($a > $b)
  echo "a is greater than b";
?>

if...else


<?php
 $a = 5;
 $b = 7;
 if($a > $b)
  echo "a is greater than b";
 else
  echo "a is less than b"; 
?>

if...elseif...else


<?php
 $a = 5;
 $b = 5;
 if($a > $b)
  echo "a is greater than b";
 elseif($a < $b)
  echo "a is less than b"; 
 else
  echo "a is equal to b";
?>

Note: If your action code is more than one statement, you must use the curly braces {}.

Comparison Operators

PHP has the following comparison operators.
==is equal to
===is identical
!=is not equal
!==is not identical
<>is not equal
>greater than
<less than
>=greater than or equal
<=less than or equal
Read more ...

Basic PHP Crash Course (part 1)

Thursday, March 22, 2012
I want to create a tutorial serie for the PHP beginner. So I have been writing this Crash Course. I think it is more interesting to learn PHP by creating the real website.

What do you need to know to learn this PHP Crash Course?

You have already know about HTML and CSS. It is more good if you know about JavaScript.

Have you ever run php script in localhost? If you haven't, read this tutorial first.

I believe that you have already known about the HTML form.

Let's start with very little web application. Assuming that we sell the pizza. So create a folder below your c:xampphtdocs folder and name it pizza_shop. And then open a new document in your favourite editor. Type below code in your new document and save as index.php in your pizza_shop folder.

<html>
<head>
 <title>Pizzs Show: Home</title>
</head>
<body>
 <h3>Pizza Shop Order Form</h3>
 <form action="process.php" method="post">
  <p>
   <label for="cus_name">Customer Name:</label>
   <input type="text" name="cus_name" />
  </p>
  <p>
   <label for="address">Shipping Address:</label>
   <input type="text" name="address" />
  </p>
  <p>
   <label for="quantity">Pizza Quantity:</label>
   <input type="text" name="quantity" />
  </p>
  <p>
   <input type="submit" name="submit" value="Submit Order" />
  </p>
 </form>
</body>
</html>

Run your browser and check this address http://localhost/pizza_shop
You will see like below screenshot.


Why? When you run your site, index.php will be called as default.

When the customer fills and submits the form, process.php page will be called because you set in the form action attribute to "process.php". The process.php file will get the form variables by using POST method because you set in from method attribute to "post". I will also explain about post method later in this post.

Now we need to create process.php. Type below code in your new document and save as process.php in your pizza_shop folder.

<html>
 <head>
  <title>Order Process</title>
 </head>
<body>
 <?php
  $cus_name = $_POST['cus_name'];
  $quantity = $_POST['quantity'];
  $address = $_POST['address'];
 ?>
 <p>Thank <?php echo $cus_name; ?> !</p>
 <p>You order <?php echo $quantity; ?> pizza.</p>
 <?php
  $total = $quantity * 10;
 ?>
 <p>It will cost you <?php echo $total; ?> $.</p>
 <p>We will send withing 2 hours to <?php echo $address; ?>.</p>
</body>
</html>

Explanation


Variable

Let me introduce you to PHP variable to understand above code.

Variable is look like a box. You can store values like string, number, object etc. And then we can reuse this variable through our code.

Have you noticed that every variable start with dollar sign($) in our site?

All variable name must start with dollar sign($) and can contain alphabetic character, under score and number. But it cannot start with number. Check below example.

$string = "Hello World!";  //Valid
$string2 = 'Hi everyone!'; //Valid

$_number = 3;   //Valid
$number = 2.2;  //valid

$flag = true;   //valid

$1number = 5;       //Invalid
$2string = "Second String"; //Invalid

The first two are assigned string. If you want to assign string value you must be use double quotes or single quotes.

The second two are integer and float numbers.

The third one is boolean and you don't need double quotes or single quotes to assign boolean value.

Last two is invalid because they start with the number.

You don't need to declare the variable type before use like C. In PHP, the type of variable is determined by the value assigned to it.
Variable names are case sensitive.

POST

There are two types to access the form variables from one page to another. They are POST and GET that you set in your html form method. They have their own usefulness. In this post I will tell you only about POST.

$_POST is the superglobal variable which contain all POST data. It is an associated array of variables passed to the current script via the HTTP POST method. They are automatically set for you by PHP.
You can access the each form field as PHP variable whose name relates to the name of the form.

Operator

We also use two operators in our pizza site. They are assignment operator equal(=) and multiplication (*).
There are many operators in PHP like other languages. I want to introduce you some operators for this post.

Assignment(=) e.g $number = 1;

Mathematical Operators
Addition (+) e.g $total = 1+1;
Subtraction (-) e.g $result = 2-1;
Division (/) e.g $result = 5/2; //result will be 2.5
Modulus (%) e.g $result = 5%2; //result will be 1
Read more ...

How to start with PHP?

Saturday, March 10, 2012

What is PHP?

PHP stands for Hypertext Preprocessor and it is a server-side scripting language for web development. Server-side means PHP code execute on the server and the plain HTML result is sent to the browser. Script means it does not need to compile to run. PHP can also be embedded into HTML.

PHP can create the very awsome website and web application. And then you can easily learn PHP if you familiar with programming like C.

What do we need to run PHP in localhost?

1. web server(Apache, IIS, etc.)
2. PHP (http://www.php.net/downloads.php)
3. MySQL (http://www.mysql.com/downloads/)

You can install these 3 programs one by one. You can get a lot of headache to do so. Today everything is easy to use. There are many packages that contain everything we need.

For Windows - WAMP, XAMPP, EasyPHP, AMPPS
For Mac - XAMPP, MAMP
For Linux - XAMPP, LAMP
For Solaris - XAMPP

These packages make your installation a breeze.

XAMPP

As for me, I use XAMPP server so I want to introduce you little about XAMPP. XAMPP can run all major Operating System.

Installation

1. Go to the XAMPP home page from this link.
2. Choose your Operating System. As for me, I choose XAMPP for Windows.
3. Download the Installer.
4. Run your downloaded Installer.

That's all. Now you are ready to write your php website.

Running your Server

Run your XAMPP Control Panel from your Desktop or start menu.

If you haven't run your Apache, click check box and start running like above screenshot.

Open you browser and run this address http://localhost/ and choose your language. You will see like below screenshot.

Congratulations:
You have successfully installed XAMPP on this system!

Writing PHP

Let's say hello to the world.
Open Nodepad. The best way to learn code is to code. So type below code in your Nodepad.

<?php
 echo "Hello World!";
?>

Save this file in your c:xampphtdocs folder as hello.php. You will need to change in "Save as type:" to "All Files" when you save your Nodepad file like below screenshot.


Run your browser and check this address http://localhost/hello.php
You will see "Hello World!" on you browser window.

How does it work?

As you have seen above code, our code started with <?php and ended with ?>. This tells your server to parse the information between them as PHP. It has three forms like below. You can use either of the options.


<?
PHP Code In Here
?>

<?php
PHP Code In Here
php?>

<script language="php">
PHP Code In Here
</script>


The echo function will display the text between double code on the browser. Have you found a semicolon at the end of the statement? Each PHP statement must end with a semicolon.

Embedding withing HTML

As you know, we are creating a website so you need to embed the PHP code withing HTML like below.


<html>
<head>
<title>My first PHP site</title>
</head>

<body>
<?php
 echo "Hello World!";
?>
</body>
</html>

If you encounter any problem, don't hesitate to ask me.
Read more ...

User friendly date with Codeigniter and MySQL

Tuesday, March 6, 2012
When we deal with the date in Codeigniter and MySQL, there is a little problem that MySQL accepts dates only in the ISO-recommended format YYYY-MM-DD. I want users to be able to enter and show dates in a more familiar format.

At here if you use a text box to enter the date, user can do many mistake. So the best way to handle the input of dates is with separate fields using HTML <select> elements or combo boxes. Let's start our project.

Requirement

CodeIgniter

Step 1: Configuration

Open application/config/database.php, and change the following database configuration to fit your mysql configuration.

$config['hostname'] = “localhost”;

$config['username'] = “myusername”;

$config['password'] = “mypassword”;

$config['database'] = “mydatabase”;

$config['dbdriver'] = “mysql”;

Then open application/config/config.php

$config['base_url'] = ‘http://localhost/ci_date’;

Open application/config/autoload.php

$autoload['libraries'] = array('database’);

and

$autoload['helper'] = array(‘url’,'form’);

Open application/config/routes.php, change default controller to user controller as we’ll create later on this tutorial.

$route['default_controller'] = ‘home’;

Creating Database table

We need to create a table in our database. Import following SQL statement via phpMyAdmin or any other MySQL tool.

CREATE TABLE `user` (
  `id` int(20) NOT NULL auto_increment,
  `name` varchar(50) NOT NULL,
  `dob` date NOT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

Designing our date input view files

Now let's create our design file. Create a blank document in the views folder (application -> views) and name it home_view.php, in the document add all the following code.

<!DOCTYPE html>
<html lang="en">
<head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
 <title><?php echo (isset($title)) ? $title : "My CI Site" ?> </title>
 <link rel="stylesheet" type="text/css" href="<?php echo base_url();?>/css/style.css" />
</head>
<body>
 <div id="wrapper">
 <div id="content">
 <?php $this->load->helper('dob'); ?>
 <div class="reg_form">
 <?php echo validation_errors('<p class="error">'); ?>
 <?php echo form_open("home/add_data"); ?>
  <p>
   <label for="user_name">User Name:</label>
   <input type="text" id="user_name" name="user_name" value="" />
  </p>
  <p>
   <label>Birthday:</label>
   <select name="month"><option value="0">Month:</option><?php echo generate_options(1,12,'callback_month')?></select>
   <select name="day"><option value="0">Day:</option><?php echo generate_options(1,31)?></select>
   <select name="year"><option value="0">Year:</option><?php echo generate_options(2011,1900)?></select>
  </p>
  <p>
   <input type="submit" class="greenButton" value="Submit" />
  </p>
 <?php echo form_close(); ?>
</div><!--<div class="reg_form">-->
</div><!--<div id="content">-->
<div id="footer">
 &copy; 2011 <a href="http://tutsforweb.blogspot.com/">TutsforWeb</a> All Rights Reserved.
</div><!-- <div class="footer">-->
</div><!--<div id="wrapper">-->
</body>
</html>

In this file, you will notice that dob helper. It is not CI built in helper. This helper is created by learning this tutorial.

Our birthday field will be look like below:

Creating dob_helper

Following code is our dob_helper.php. Create a blank document in the helpers floder (application -> helpers) and name it dob_helper.php, in the document add all the following code.

<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
if ( ! function_exists('generate_options'))
{
 function generate_options($from,$to,$callback=false)
 {
  $reverse=false;
  if($from>$to)
  {
   $tmp=$from;
   $from=$to;
   $to=$tmp;
   $reverse=true;
  }
  $return_string=array();
  for($i=$from;$i<=$to;$i++)
  {
   $return_string[]='
   <option value="'.$i.'">'.($callback?$callback($i):$i).'</option>
   ';
  }
  if($reverse)
  {
   $return_string=array_reverse($return_string);
  }
  return join('',$return_string);
 }
}
if ( ! function_exists('callback_month'))
{
 function callback_month($month)
 {
  return date('F',mktime(0,0,0,$month,1));
 }
}
if ( ! function_exists('format_date'))
{
 function format_date($date)
 {
  $parts = explode('-',$date);
  return date('F j, Y',mktime(0,0,0,$parts[1],$parts[2],$parts[0]));
 }
}
?>

In our helper, it has three functions generate_options(), callback_month() and format_date(). We used the generate_options() and callback_month() in our html select element to fill the data. The format_date() function will be used when we display the date to the user.

Check the input date in the Controller

Create a blank document in the controllers folder (application -> controllers) and name it home.php, in the document add all the following code.

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Home extends CI_Controller{
 public function __construct(){
  parent::__construct();
  $this->load->model('home_model');
 }
 public function index()
 {
  $this->load->view('home_view');
 }
 public function add_data()
 {
  $_POST['dob'] = $_POST['year'].'-'.$_POST['month'].'-'.$_POST['day'];
  $this->load->library('form_validation');
  // field name, error message, validation rules
  $this->form_validation->set_rules('user_name', 'User Name', 'trim|required|min_length[4]|xss_clean');
  $this->form_validation->set_rules('dob', 'Date of Birth', 'callback_date_check');
  if ($this->form_validation->run() == FALSE)
  {
   $this->load->view('home_view');
  }
  else
  {
   $this->home_model->save_data();
   $this->show();
  }
 }
 public function date_check()
 {
  if(checkdate($_POST['month'],$_POST['day'],$_POST['year']))
  {
   return TRUE;
  }
  else
  {
   $this->form_validation->set_message('date_check', 'Correct you Date of Birth.');
   return FALSE;
  }
 }
 public function show()
 {
  $this->load->model('home_model');
  $data['query']=$this->home_model->get_all();
  $this->load->view('dateshow_view',$data);
 }
}
?>

In our add_data() function, firstly we set the $_POST['dob'] from our three html select boxes by concatenating '-' between them. Now our dob post data is ready to add to the MySQL database. There's just one problem with this: someone might enter an invalid date, such as February 31 or September 31. So, it's a good idea to use the PHP checkdate() function to make sure the date is valid.

So when we set the form validation rule for our dob (Date of Birth) field, we use the callback function as date_check(). You can easily follow our date_check() function I think.

Showing our user friendly date

Let's create our dateshow_view.php to test the format_date() function from our dob_helper. Create a blank document in the views folder (application -> views) and name it dateshow_view.php, in the document add all the following code.

<!DOCTYPE html>
<html lang="en">
<head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
 <title><?php echo (isset($title)) ? $title : "My CI Site" ?> </title>
 <link rel="stylesheet" type="text/css" href="<?php echo base_url();?>/css/style.css" />
</head>
<body>
<div id="wrapper">
<div id="content">
 <?php $this->load->helper('dob'); ?>
 <?php    foreach($query as $row){?>
  <p>
  <?php
   echo format_date($row->dob);
  ?>
  </p>
 <?php }?>
</div>
</div>
</body>
</html>

It will display our date as below picture.


Creating Model

Our model is very simple. Create a blank document in the models folder (application -> models) and name it home_model.php, in the document add all the following code.

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Home_model extends CI_Model {
 public function __construct()
 {
  parent::__construct();
 }
 public function save_data()
 {
  $data=array(
   'name'=>$this->input->post('user_name'),
   'dob'=>$this->input->post('dob')
  );
  $this->db->insert('user',$data);
 }
 function get_all()
 {
  $query=$this->db->get('user');
  return $query->result();
 }
}

Designing with CSS

Create a folder named css in your root directory and save following code as a sytle.css.

@charset "utf-8";
/* CSS Document */
body{
 background-color:#FFF;
 font-family:Monaco,Consolas,'Lucida Grande','Lucida Console';
 font-size:16px;
 text-shadow:rgba(0,0,0,0.01) 0 0 0;
}
#wrapper{
 width:960px;
 margin:0 auto;
}
#content{
 width:960px;
 margin:5px;
 float:left;
}
/************************************************/
.reg_form{
 width:460px;
 padding:20px;
 margin:0 auto;
 border:3px solid #DFDFDF;
 background: -webkit-gradient(linear, left top, left bottom, from(#fff), to(#cbd4e5));
 background: -moz-linear-gradient(top,  #fff,  #cbd4e5);
 filter:  progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff', endColorstr='#cbd4e5');
}
.reg_form p{
 width: 300px;
 clear: left;
 margin: 0;
 padding: 5px 0 8px 0;
 padding-left: 155px;
 border-top: 1px dashed gray;
 height: 1%;
}
.reg_form label{
 font-weight: bold;
 float: left;
 margin-left: -155px;
 width: 150px;
}
input,select{
 padding:3px;
 color:#333333;
 border:1px solid #96A6C5;
 margin-top:2px;
 width:180px;
 font-size:11px;
}
select{
 width:auto;
 padding:2px;
}
.greenButton{
 width:auto;
 margin:10px 0 0 2px;
 padding:3px 4px 3px 4px;
 color:white;
 background-color:#589d39;
 outline:none;
 border:1px solid #006600;
 font-weight:bold;
}
.greenButton:active{
 background-color:#006600;
 padding:4px 3px 2px 5px;
}

Download Source Code
Read more ...

Captcha in Codeigniter with session

Friday, March 2, 2012
In this tutorial I will show you how to use the the codeigniter captcha helper. I use the session to save the captcha data instead of database.

Configuration

Download the CI latest version form codeigniter.com. Extract and rename as ci_captcha.

Open application/config/database.php, and change the following database configuration to fit your mysql configuration.

$config['hostname'] = “localhost”;

$config['username'] = “myusername”;

$config['password'] = “mypassword”;

$config['database'] = “mydatabase”;

$config['dbdriver'] = “mysql”;

Then open application/config/config.php

$config['base_url'] = ‘http://localhost/ci_captcha/’;

$config['encryption_key'] = '1234';

Open application/config/autoload.php

$autoload['libraries'] = array('database’,'session');

and

$autoload['helper'] = array(’form’);

Open application/config/routes.php, change default controller to home controller that we’ll create later on this tutorial.

$route['default_controller'] = ‘home’;

The last thing we need to do for this step is create a folder called captcha under the ci_captcha folder.

Creating Database table

We need to create a table in our database. Import following SQL statement via phpMyAdmin or any other MySQL tool.

CREATE TABLE `message` (
`id` INT( 50 ) NOT NULL AUTO_INCREMENT ,
`username` VARCHAR( 50 ) NOT NULL ,
`message` TEXT NOT NULL ,
PRIMARY KEY ( `id` )
) ENGINE = InnoDB

Controller

Create a blank document in the controller file (application -> controller) and name it home.php, in the document add all the following code.

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Home extends CI_Controller {
 public function __construct()
 {
  parent::__construct();
  $this->load->model('home_model');
 }
 public function index()
 {
  $this->load->helper('captcha');
  $vals = array(
     'img_path' => './captcha/',
     'img_url' => 'http://localhost/ci_captcha/captcha/'
     );
  $cap = create_captcha($vals);
  $data = array(
     'captcha_time' => $cap['time'],
     'ip_address' => $this->input->ip_address(),
     'word' => $cap['word']
     );
  $this->session->set_userdata($data);
  $data['cap_img']=$cap['image'];
  $this->load->view('form_view',$data);
 }
 public function add_message()
 {
  $this->load->library('form_validation');
  // field name, error message, validation rules
  $this->form_validation->set_rules('user_name', 'User Name', 'trim|required|min_length[3]');
  $this->form_validation->set_rules('message', 'Message', 'trim|required|xss_clean');
  $this->form_validation->set_rules('captcha', 'Security Code', 'trim|required|callback_check_captcha');
  if($this->form_validation->run() == FALSE)
  {
   $this->index();
  }
  else
  {
   $this->home_model->add_message();
  }
 }
 public function check_captcha()
 {
  $expiration = time()-7200; // Two hour limit
  $cap=$this->input->post('captcha');
  if($this->session->userdata('word')== $cap 
   AND $this->session->userdata('ip_address')== $this->input->ip_address()
   AND $this->session->userdata('captcha_time')> $expiration)
  {
   return true;
  }
  else{
   $this->form_validation->set_message('check_captcha', 'Security number does not match.');
   return false;
  }
 }
}
?>

View

Create a blank document in the views file (application -> views) and name it form_view.php, in the document add all the following code.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Captcha in Codeigniter</title>
</head>
<body>
 <?php echo validation_errors('<p>'); ?>
 <?php echo form_open("home/add_message"); ?>
 <p>
  <label for="user_name">Name:</label>
  <input type="text" id="user_name" name="user_name" value="<?php echo set_value('user_name'); ?>" />
 </p> 
 <p>
  <label for="con_password">Message:</label>
  <textarea name="message" id="message" value="" cols="50" rows="4"></textarea>
 </p> 
 <p>
  <?php echo $cap_img ?>
  <input type="text" id="captcha" name="captcha" value="" />
 </p> 
 <p>
  <input type="submit" value="Submit" />
 </p>
 <?php echo form_close(); ?>
</body>
</html>

Model

Create a blank document in the models file (application -> models) and name it home_model.php, in the document add all the following code.

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Home_model extends CI_Model {
 public function __construct()
 {
  parent::__construct();
 }
 public function add_message()
 {
  $data=array(
     'username'=>$this->input->post('user_name'),
     'message'=>$this->input->post('message'),
     );
  $this->db->insert('message',$data);
 }
}
?>

Now you have done a from with captcha. All above code is easy to follow and understand, isn't it? But if you have some trouble, don't hesitate to asked me.
Read more ...