Pages

Showing posts with label codeigniter. Show all posts
Showing posts with label codeigniter. Show all posts

Codeigniter Template Library for Wordpress Fun

Thursday, May 24, 2012
I am not only a Codeigniter fun but also Wordpress fun. So I try to crate a CI template library that look like Wordpress theme.

I have got this library and it will be used with the helper together.

By using this library, you can crate the themes like in Wordpress.

Requirement

Codeigniter 2.0.0 and above

Installing

Copy and paste below code in your new document and save as

./application/libraries/Template.php

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
  /**
  * Template
  * 
  * Wordpress like template for CodeIgniter
  * 
  * @package  Template
  * @version  0.1.0
  * @author  TutsforWeb <http://tutsforweb.blogspot.comt>
  * @link   
  * @copyright  Copyright (c) 2011, TutsforWeb
  * @license  http://opensource.org/licenses/mit-license.php MIT Licensed
  * 
  */

  class Template
  {
   private $ci;
   private $tp_name;
   private $data = array();

   public function __construct() {
    $this->ci = &get_instance();
   }

   public function set($name='') {
    $this->tp_name = $name;
   }

   public function load($name = 'index') {
    $this->load_file($name);
   }

   public function get_header($name) {
    if(isset($name)) {
     $file_name = "header-{$name}.php";
     $this->load_file($file_name);
    }
    else {
     $this->load_file('header');
    }
   }

   public function get_sidebar($name) {
    if(isset($name)) {
     $file_name = "sidebar-{$name}.php";
     $this->load_file($file_name);
    }
    else {
     $this->load_file('sidebar');
    }
   }

   public function get_footer($name) {
    if(isset($name)) {
     $file_name = "footer-{$name}.php";
     $this->load_file($file_name);
    }
    else {
     $this->load_file('footer');
    }
   }

   public function get_template_part($slug, $name) {
    if(isset($name)) {
     $file_name = "{$slug}-{$name}.php";
     $this->load_file($file_name);
    }
    else{
     $this->load_file($slug);
    }
   }

   public function load_file($name)
   {
    if($this->get_data($name))
    {
     $data = $this->get_data($name);
     $this->ci->load->view($this->tp_name.'/'.$name,$data);
    }
    else {
     $this->ci->load->view($this->tp_name.'/'.$name);
    }
   }

   public function set_data($key, $data) {
    $this->data[$key] = $data;
   }

   public function get_data($key) {
    if(isset($this->data[$key])) {
     return $this->data[$key];
    }
    else {
     return false;
    }
   }
  }
?>
(or)
Download from below button and place that file to './application/libraries/' directory.
Download Source Code

Copy and paste below code in your new document and save as

./application/helpers/template_helper.php

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
 /**
  * Template
  *
  * WordPress like template for CodeIgniter
  *
  * @package  Template
  * @subpackage Helpers
  * @version  0.1.0
  * @author  TutsforWeb <http://tutsforweb.blogspot.com>
  * @link   
  * @copyright  Copyright (c) 2011, TutsforWeb
  * @license  http://opensource.org/licenses/mit-license.php MIT Licensed
  *
  */
  
  if ( ! function_exists('get_header'))
  {
   function get_header($name=null)
   {
    $ci =& get_instance();
    return $ci->template->get_header($name);
   }
  }

  if ( ! function_exists('get_sidebar'))
  {
   function get_sidebar($name=null)
   {
    $ci =& get_instance();
    return $ci->template->get_sidebar($name);
   }
  }

  if ( ! function_exists('get_footer'))
  {
   function get_footer($name=null)
   {
    $ci =& get_instance();
    return $ci->template->get_footer($name);
   }
  }

  if ( ! function_exists('get_template_part'))
  {
   function get_template_part($slug, $name=null)
   {
    $ci =& get_instance();
    return $ci->template->get_template_part($slug, $name);
   }
  }
?>
(or)
Download from below button and place that file to './application/helpers/' directory.
Download Source Code

Loading Template

Then open your autoload.php from your './application/config/' directory and set
$autoload['libraries'] = array('template');
and
$autoload['helper'] = array('template');
(or)
You can load Template just like any other library and helper in your controller using the $this->load->library function:
$this->load->library('template');
$this->load->helper('template');

Usage

Creating our theme

Now we can start to write our theme.
Create a folder in your views folder named default.
Let's start with header.php. Copy and paste the following code in you new document and save as header.php in your default theme folder like below.
./application/views/default/header.php
<html>
<head>
<title>Home</title>
</head>
<body>
<div id="pagewrap">
 <div id="header">
  <h1>Your Site Name</h1>
 </div><!-- /#header -->
Next one is footer. Copy and paste the following code in you new document and save as footer.php in your default theme folder like below.
./application/views/default/footer.php

 <div id="footer">
  <p>Design by <a href="http://tutsforweb.blogspot.com">Web In One</a></p>
 </div><!-- /#footer --> 

</div><!-- /#pagewrap -->
</body>
</html>

Next one is sidebar. Copy and paste the following code in you new document and save as footer.php in your default theme folder like below.
./application/views/default/sidebar.php

<div id="sidebar">
 <h2>This is side bar.</h2>
</div><!-- /#sidebar -->

Before we do not write index.php, I want to introduce you some function.
get_header();
get_footer();
get_sidebar();
If you call above function in your view file, it will load your header.php, footer.php and sidebar.php respectively from your theme folder. And then you can also call with the parameter like below.
get_header('primary');
get_footer('primary');
get_sidebar('left');
If you call like above, it will load your header-primary.php, footer-primary.php and sidebar-left.php respectively look like in Wordpress.

Now let's start our index file. Copy and paste the following code in you new document and save as index.php in your default theme folder like below.
./application/views/default/index.php
<?php get_header(); ?>
<div id="content">
 <h2>Content</h2>
  <p>This is content from index.</p>
</div><!--<div id="content">-->
<?php
get_sidebar(); 
get_footer();
?>

The last function for your view file is get_template_part(). It can call any other view file by writing like below.
get_template_part('about');
The above function will load the about.php from your theme folder.

You can also call with two parameter like below.
get_template_part('about','other');
The above function will load the about-other.php from your theme folder.

Controller

$this->template->set()

Firstly you need to set the theme name in your controller.
Assuming that you have tow themes like below.

./application/views/default/index.php
./application/views/default/header.php
./application/views/default/footer.php
./application/views/default/sidebar.php
./application/views/default/about.php
and
./application/views/newtheme/index.php
./application/views/newtheme/header.php
./application/views/newtheme/footer.php
./application/views/newtheme/sidebar.php
./application/views/newtheme/project.php

Now you have two themes named default and newtheme.
In your controller you need to set a theme you want to use like below.

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Home extends CI_Controller{
 public function __construct() {
  parent::__construct();
 }
 
    public function index() {
  $this->template->set('default');
 }
}
?>

$this->template->load()

Now you can load your theme.
If you load with no parameter, it will load index.php like below.

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Home extends CI_Controller{
 public function __construct() {
  parent::__construct();
 }
 
    public function index() {
  $this->template->set('default');
         $this->template->load();
 }
}
?>

If you load with the parameter, it will load the view file that you set as parameter as below.

$this->template->set('default');
$this->template->load('about');

$this->template->set_data()


If you want to pass your data from controller to view, you must use this function. Let's discuss how to use this function in your controller and in your view file.

Now we want to pass our title from our controller to view file. Below is controller syntax:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Home extends CI_Controller{
 public function __construct(){
  parent::__construct();
 }

 public function index() {
  $this->template->set('default');
  $header_data['title'] = "TutsforWeb: Web design and developmetn tutorials";
  $this->template->set_data('header',$header_data);
  $this->template->load();
 }
}
?>
First parameter is your view file name.
You can you in your header.php view file as you used in CI view file like below.

<html>
<head>
 <title><?php echo $title; ?></title>
</head>
<body>
<div id="pagewrap">
 <div id="header">
  <h1>Your Site Name</h1>
 </div><!-- /#header -->

If you have any other tips, techniques or requirement, let us know in the comments.
Read more ...

Date validation for Codeigniter 2

Wednesday, May 23, 2012
I wrote a tutorial here about the CI date. At that post I used the HTML <select> for the input of date. Sometime our client can want to use text box for the date input. We need the validation for this date. I have found this code from here. It is for CI 1.7.* and PHP 5.2.*. So I change some code for the CI 2.0.* and PHP 5.3.*.

To use, copy the class below into your application/libraries folder named MY_Form_validation.php, then in your controller use it like any other rule.

Form

This validation rule validates an input text box only right now.

<input type="text" name="date" value="<?php echo set_value('date'); ?>" size="10" />

Controller Usage


UK

$this->form_validation->set_rules('date', 'date', 'trim|required|valid_date[d/m/y,/]');

US

$this->form_validation->set_rules('date', 'date', 'trim|required|valid_date[m/d/y,/]');

Database

$this->form_validation->set_rules('date', 'date', 'trim|required|valid_date[y-m-d,-]');

Code


<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class MY_Form_validation extends CI_Form_validation {

 function __construct(){
  parent::__construct();
 }

 /**
 * @desc Validates a date format
 * @params format,delimiter
 * e.g. d/m/y,/ or y-m-d,-
 */
 function valid_date($str, $params)
 {
  // setup
  $CI =&get_instance();
  $params = explode(',', $params);
  $delimiter = $params[1];
  $date_parts = explode($delimiter, $params[0]);

  // get the index (0, 1 or 2) for each part
  $di = $this->valid_date_part_index($date_parts, 'd');
  $mi = $this->valid_date_part_index($date_parts, 'm');
  $yi = $this->valid_date_part_index($date_parts, 'y');

  // regex setup
  $dre =   "(0?1|0?2|0?3|0?4|0?5|0?6|0?7|0?8|0?9|10|11|12|13|14|15|16|17|18|19|20|21|22|23|24|25|26|27|28|29|30|31)";
  $mre = "(0?1|0?2|0?3|0?4|0?5|0?6|0?7|0?8|0?9|10|11|12)";
  $yre = "([0-9]{4})";
  $red = ''.$delimiter; // escape delimiter for regex
  $rex = "/^[0]{$red}[1]{$red}[2]/";

  // do replacements at correct positions
  $rex = str_replace("[{$di}]", $dre, $rex);
  $rex = str_replace("[{$mi}]", $mre, $rex);
  $rex = str_replace("[{$yi}]", $yre, $rex);

  if (preg_match($rex, $str, $matches))
  {
   // skip 0 as it contains full match, check the date is logically valid
   if (checkdate($matches[$mi + 1], $matches[$di + 1], $matches[$yi + 1]))
   {
    return true;
   }
   else
   {
    // match but logically invalid
    $CI->form_validation->set_message('valid_date', "The date is invalid.");
    return false;
   }
  }

  // no match
  $CI->form_validation->set_message('valid_date', "The date format is invalid. Use {$params[0]}");
  return false;
 }

 function valid_date_part_index($parts, $search)
 {
  for ($i = 0; $i <= count($parts); $i++)
  {
   if ($parts[$i] == $search)
   {
    return $i;
   }
  }
 }
}
?>
`
Read more ...

jQuery Ajax form validation in Codeigniter

Sunday, May 20, 2012
This tutorial is part 2 of User Registration with Codeigniter. In the previous tutorial, we do the form validation in the sever side. In this tutorial, we will do the form validation by using the ajax technology. So user can know whether his/her form valid or not before submitting.

Requirement

CodeIgniter
jQuery

Our last screen shot


Create a folder named js in your root directory and then download the jQuery file below your js folder. Rename it as jquery.js. And then link this file in our header_view.php like following.
<script type="text/javascript" src="<?php echo base_url();?>js/jquery.js"></script>

Editing registration_view file for ajax validation

Firstly I add the span class to the user_name input field to show our yes or no picture like following.
<p>
 <label for="user_name">User Name:</label>
<input type="text" id="user_name" name="user_name" value="<?php echo set_value('user_name'); ?>" /><span id="usr_verify" class="verify"></span>
</p>
And then add the following script to our registration_view.php.
<script type="text/javascript">
$(document).ready(function(){
 $("#user_name").keyup(function(){
  if($("#user_name").val().length >= 4)
  {
  $.ajax({
   type: "POST",
   url: "<?php echo base_url();?>index.php/user/check_user",
   data: "name="+$("#user_name").val(),
   success: function(msg){
    if(msg=="true")
    {
     $("#usr_verify").css({ "background-image": "url('<?php echo base_url();?>images/yes.png')" });
    }
    else
    {
     $("#usr_verify").css({ "background-image": "url('<?php echo base_url();?>images/no.png')" });
    }
   }
  });
  }
  else 
  {
   $("#usr_verify").css({ "background-image": "none" });
  }
 });
});
</script>
We use the jQuery keyup function to test whether the user already exit or not. Before we use the jQuey ajax, we need to test whether the user_name field val().length is greater than or equal 4. If the length is greater than or equal 4, we use the jQuery ajax function. In the url I give the function check_user. So in our controller, we must add that controller. Following is our check_user function. Add that function to our user controller.
public function check_user()
{
 $usr=$this->input->post('name');
 $result=$this->user_model->check_user_exist($usr);
 if($result)
 {
  echo "false";
  }
 else{
  echo "true";
  }
}
In the check_user() function, we set the $usr variable from our ajax data parameter. And then we call the model function check_user_exist. This function will return true if the user name already exits. It will return false if the user name does not exist. How do we echo for our ajax success function? So I echo the false if the user name already exits and true if the user name does not exit. We get this echoed data as a msg in the ajax success function. So we add the css background image as the yes.png if the msg is equal to true. Else we will add no.png.

Now we need to create the check_user_exist() model function. Add following function to our user_model model.
public function check_user_exist($usr)
{
 $this->db->where("username",$usr);
 $query=$this->db->get("user");
 if($query->num_rows()>0)
 {
  return true;
 }
 else
 {
  return false;
 }
}
The last thing we need to do is to add css class .verify for our image.
.verify
{
    margin-top: 4px;
    margin-left: 9px;
    position: absolute;
    width: 16px;
    height: 16px;
}
In my source code, I also add password and email validation. Download the source code and you can learn more.
Download Source Code
Read more ...

User Registration with Codeigniter

Sunday, May 20, 2012
In this tutorial, I will explain you user registration with CI. If you are a very newbies in CI, you can start by reading How to start with CI? or read this excellent article Everything You Need to Get Started With CodeIgniter.

If you have finished our previous tutorial, we can start this tutorial now. The CI classes we have to learn in this tutorial are session and form validation. I believe that you would be familiar with PHP session.

Requirement

Download the latest CI version from the following link.

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_user';

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

 

Open application/config/autoload.php

$autoload['libraries'] = array('session','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'] = 'user';

Step 2:Creating User 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( 50 ) NOT NULL AUTO_INCREMENT ,
`username` VARCHAR( 50 ) NOT NULL ,
`email` VARCHAR( 100 ) NOT NULL ,
`password` VARCHAR( 255 ) NOT NULL ,
PRIMARY KEY ( `id` )
) ENGINE = InnoDB

Step 3:Creating our Controller

Create a blank document in the controller file (application -> controller) and name it user.php, in the document add all the following code.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class User extends CI_Controller{
 public function __construct()
 {
  parent::__construct();
  $this->load->model('user_model');
 }
 public function index()
 {
  if(($this->session->userdata('user_name')!=""))
  {
   $this->welcome();
  }
  else{
   $data['title']= 'Home';
   $this->load->view('header_view',$data);
   $this->load->view("registration_view.php", $data);
   $this->load->view('footer_view',$data);
  }
 }
 public function welcome()
 {
  $data['title']= 'Welcome';
  $this->load->view('header_view',$data);
  $this->load->view('welcome_view.php', $data);
  $this->load->view('footer_view',$data);
 }
 public function login()
 {
  $email=$this->input->post('email');
  $password=md5($this->input->post('pass'));

  $result=$this->user_model->login($email,$password);
  if($result) $this->welcome();
  else        $this->index();
 }
 public function thank()
 {
  $data['title']= 'Thank';
  $this->load->view('header_view',$data);
  $this->load->view('thank_view.php', $data);
  $this->load->view('footer_view',$data);
 }
 public function registration()
 {
  $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('email_address', 'Your Email', 'trim|required|valid_email');
  $this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[4]|max_length[32]');
  $this->form_validation->set_rules('con_password', 'Password Confirmation', 'trim|required|matches[password]');

  if($this->form_validation->run() == FALSE)
  {
   $this->index();
  }
  else
  {
   $this->user_model->add_user();
   $this->thank();
  }
 }
 public function logout()
 {
  $newdata = array(
  'user_id'   =>'',
  'user_name'  =>'',
  'user_email'     => '',
  'logged_in' => FALSE,
  );
  $this->session->unset_userdata($newdata );
  $this->session->sess_destroy();
  $this->index();
 }
}
?>
In the index() function,

if(($this->session->userdata('user_name')!=""))

the above code is equal to the following code in php.

if($_SESSION['user_name']!="")

It means that if the user_name is not equal to the null, this user have already logged in. So we will go to welcome() function. Else we will show registration from view.

You will understand next login() and thank() functions I think.

In the registration() function, firstly we load the form_validation library. And then we set the rules for our form field. The trim rule is equal to the php trim() function and you will understand the others I think. And then we run the form validation. If the result is false, we will go to index() function. Else we will add user data and will go to thank() function.

In the logout() function, we will unset and destroy the session data and will go to the index() function.

Step 4:Creating Model

Create a blank document in the model file (application -> model) and name it user_model.php, in the document add all the following code.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class User_model extends CI_Model {
 public function __construct()
 {
  parent::__construct();
 }
 function login($email,$password)
 {
  $this->db->where("email",$email);
  $this->db->where("password",$password);

  $query=$this->db->get("user");
  if($query->num_rows()>0)
  {
   foreach($query->result() as $rows)
   {
    //add all data to session
    $newdata = array(
      'user_id'  => $rows->id,
      'user_name'  => $rows->username,
      'user_email'    => $rows->email,
      'logged_in'  => TRUE,
    );
   }
   $this->session->set_userdata($newdata);
   return true;
  }
  return false;
 }
 public function add_user()
 {
  $data=array(
    'username'=>$this->input->post('user_name'),
    'email'=>$this->input->post('email_address'),
    'password'=>md5($this->input->post('password'))
  );
  $this->db->insert('user',$data);
 }
}
?>
In the login() function,

$this->db->where("email",$email);

$this->db->where("password",$password);

the above two line will produce the following query in MySQL:

WHERE email='$email' AND password='$password'

$this->session->set_userdata($newdata);

This above code will set our user data to the session variable.

Step 5:Designing our view files

Create a blank document in the views file (application -> views) and name it header_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">
Create a blank document in the views file (application -> views) and name it footer_view.php, in the document add all the following code.
<div id="footer">
  &copy; 2011 <a href="http://tutsforweb.blogspot.com/">TutforWeb</a> All Rights Reserved.
 </div><!-- <div class="footer">-->
 </div><!--<div id="wrapper">-->
</body>
</html>
Now let's create our registration view file.

I will use the tableless form design. It has some benefits:

1.Faster loading of pages

2.Efficiency

3.Consistency

4.SEO advantage

5.Layouts and design sophistication

6.Bandwidth efficiency

Create a blank document in the views file (application -> views) and name it registration_view.php, in the document add all the following code.
<div id="content">
<div class="signup_wrap">
<div class="signin_form">
 <?php echo form_open("user/login"); ?>
  <label for="email">Email:</label>
  <input type="text" id="email" name="email" value="" />
  <label for="password">Password:</label>
  <input type="password" id="pass" name="pass" value="" />
  <input type="submit" class="" value="Sign in" />
 <?php echo form_close(); ?>
</div><!--<div class="signin_form">-->
</div><!--<div class="signup_wrap">-->
<div class="reg_form">
<div class="form_title">Sign Up</div>
<div class="form_sub_title">It's free and anyone can join</div>
 <?php echo validation_errors('<p class="error">'); ?>
 <?php echo form_open("user/registration"); ?>
  <p>
  <label for="user_name">User Name:</label>
  <input type="text" id="user_name" name="user_name" value="<?php echo set_value('user_name'); ?>" />
  </p>
  <p>
  <label for="email_address">Your Email:</label>
  <input type="text" id="email_address" name="email_address" value="<?php echo set_value('email_address'); ?>" />
  </p>
  <p>
  <label for="password">Password:</label>
  <input type="password" id="password" name="password" value="<?php echo set_value('password'); ?>" />
  </p>
  <p>
  <label for="con_password">Confirm Password:</label>
  <input type="password" id="con_password" name="con_password" value="<?php echo set_value('con_password'); ?>" />
  </p>
  <p>
  <input type="submit" class="greenButton" value="Submit" />
  </p>
 <?php echo form_close(); ?>
</div><!--<div class="reg_form">-->
</div><!--<div id="content">-->
In this view we echo our validation errors like below.

<?php echo validation_errors('<p>'); ?>

In our input fields, we use the below function.

<?php echo set_value('user_name'); ?>

Because of above function the original data will be show in the form, if there is an error after the validation rules. So we have only been dealing with errors.

Below code is thank_view.php and welcome_view.php.
<div id="content">
<div class="signup_wrap">
<div class="signin_form">
 <?php echo form_open("user/login"); ?>
  <label for="email">Email:</label>
  <input type="text" id="email" name="email" value="" />
  <label for="pass">Password:</label>
  <input type="password" id="pass" name="pass" value="" />
  <input type="submit" class="" value="Sign in" />
 <?php echo form_close(); ?>
</div><!--<div class="signin_form">-->
</div><!--<div class="signup_wrap">-->
<h1>Thank!</h1>
</div><!--<div id="content">-->
<div class="content">
  <h2>Welcome Back, <?php echo $this->session->userdata('username'); ?>!</h2>
  <p>This section represents the area that only logged in members can access.</p>
  <h4><?php echo anchor('user/logout', 'Logout'); ?></h4>
</div><!--<div class="content">-->
We need some css code to design our registration form. Copy following code and paste your css>style.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;
}
/************************************************/
.signup_wrap{
height:25px;
width:100%;
padding:5px;
background-color:#2A1FFF;
}
.signin_form{
float:right;
}
.signin_form input{
width:80px;
}
.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');
}
.form_title,
.form_sub_title{
font-size:20px;

font-family:"Lucida Grande",Tahoma,Verdana,Arial,sans-serif;
font-size:20px;
font-weight:bold;
}
.form_sub_title{
font-weight:normal;
padding:6px 0 15px 0;
}
.reg_form p{
width: 300px;
clear: left;
margin: 0;
padding: 5px 0 8px 0;
padding-left: 155px; /*width of left column containing the label elements*/
border-top: 1px dashed gray;
height: 1%;
}
.reg_form label{
font-weight: bold;
float: left;
margin-left: -155px; /*width of left column*/
width: 150px; /*width of labels. Should be smaller than left column (155px) to create some right margin*/
}
input{
padding:3px;
color:#333333;
border:1px solid #96A6C5;
margin-top:2px;
width:180px;
font-size:11px;
}
.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;
}
.error{
color:#F00;
}
#footer{
color:#fff;
padding-top:20px;
text-align:center;
background: #454546; 
height: 20px;
clear:both;
}
Now our form is finished. Don’t hesitate to ask me, if something goes wrong on your side.
In the next tutorial we will discuss jQuery Ajax with CI.
Download Source Code
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 ...

Codeigniter Pagination

Sunday, February 26, 2012
This tutorial is part 2 of the tutorial series Building Website with CI.

In this part 2 will explain you about Codeigniter Pagination Class.

What is Pagination?

If you are not familiar with the term "pagination", it refers to links that allows you to navigate from page to page, like this:


We crated a site like facebook in the part 1 (How to start with CI?). In this part we will add the pagination to our site.

Controller

I added some chunk of code to our controller index function like following.

public function index()
    {
        $data['base']=$this->config->item('base_url');
        $data['title']= 'Message form';
        $this->load->model("message_model");

        $total=$this->message_model->message_count();
        $per_pg=5;
        $offset=$this->uri->segment(3);

        $this->load->library('pagination');
        $config['base_url'] = $data['base'].'/index.php/home/index/';
        $config['total_rows'] = $total;
        $config['per_page'] = $per_pg;
        $config['full_tag_open'] = '<div id="pagination">';
        $config['full_tag_close'] = '</div>';

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

        $data['query']=$this->message_model->get_all($per_pg,$offset);
        $this->load->view('header_view',$data);
        $this->load->view('messageform_view',$data);
        $this->load->view('footer_view',$data);
    }

Don't worry if you don't understand above code. I will explain you.

The first line I have added is

$total=$this->message_model->message_count();

This line will grab the total number of rows from our database table. To get the total number of rows, we have to add the message_count() function to our message_model model. I will show you writing message_count() function in our model section. Now we have got the total number of rows from our database table.

Next we create a variable $per_pg for our pagination class. This variable is to adjust how many rows to display in each page.

Next we read the value of the third segment of the URI which is the current offset number to a variable called $offset. If the segment is empty the we set the value as 0.

Here we need to understand about CI URLs structure. CI’s URLs usually take the following form,

www.examlple.com/index.php/class/function/ID,

so as you can see the 3rd segment (after index.php) represents the ID. So lets take for example the following URL:

http://www.example.com/index.php/home/index/5

The ID number will depend on our $per_pg ( per page) variable. If we set the per page as 5, our ID number will go 5,10,15,... If we set the per page as 10, our ID number will go 10,20,30,... So this is offset value for our database query.

Next we load the pagination library. It is required if you will be accessing any of its methods.

Next we need to set the values to config our pagination.
$config['base_url'] = $data['base'].'/index.php/home/index/';
First one is base_url that the base URL of the web page to be paginated. Base URL from config file and concatenated to that is the remainder of the URL necessary to reference the web page to be paginated.
$config['total_rows'] = $total;
We have already got this variable as $total. So set it up.
$config['per_page'] = $per_pg;
We have already created this one first so set it up.
$config['full_tag_open'] = '<div id="pagination">';
$config['full_tag_close'] = '</div>';

Above two lines are for our pagination design. First one will appear before the pagination link and second one will appear after the pagination link.

$this->pagination->initialize($config);
$data['pagination']=$this->pagination->create_links();
In above two lines, first one is initialize our pagination class. Second one is create a link and return the value and set it to our $data variable array as pagination variable. We will use this variable in our view file.

In part 1 of our controller, we grab all data from our database like this:

$data['query']=$this->message_model->get_all();

To add the pagination, we need to pay the limit and offset as the parameters for our database query.

Limit determine how many rows we want to grab from our database table or how many rows to display in each page and offset which will it what row to start returning results from.

So our code will be look like this
$data['query']=$this->message_model->get_all($per_pg,$offset);
Rest of our code is like part 1.

Model

I rewrote the get_all() function and added message_count() function to count the total rows from our message table like following.

public function get_all($per_pg,$offset)
    {
 $this->db->order_by('id','desc');
        $query=$this->db->get('message',$per_pg,$offset);
        return $query->result();
    }
    public function message_count()
    {
        return $this->db->count_all('message');
    }

As you saw in the controller the method will have two arguments, one for the limit or per page and the other for the offset. So you will notice we called the two arguments to get_all(), $per_pg and $offset respectively. $per_pg specifies the number of results to retrieve from the database and $offset specifies where it should start retrieving results from.
$this->db->order_by('id','desc');
The above code will produce the following query in MySQL:
ORDER BY id DES
$this->db->get('message',$per_pg,$offset);
The above code will produce the following query in MySQL:
SELECT * FROM message LIMIT 5, 0

So because of these two lines, query in MySQL will be: SELECT * FROM message ORDER BY id DESC LIMIT 5, 0

And then I will explain you about message_count() function.
public function message_count()
{
     return $this->db->count_all('message');
}
It is so clear. It will return the number of rows in a particular table as an integer. Submit the table name in the parameter.

View

In view file, we only need to do is echoing our pagination variable in a rightful place. So we have to add below code after the foreach loop in our messageform_view view file.

echo $pagination;

Styling with css

We should add some style to our style.css for our pagination. We wrapped the pagination with div id named pagination in our controller. So add below css code to our style.css.

#pagination{
    float: left;
    font:11px Tahoma, Verdana, Arial, "Trebuchet MS", Helvetica, sans-serif;
    color:#3d3d3d;
    margin-top: 20px;
    margin-left:auto;
    margin-right:auto;
    margin-bottom:20px;
    width:100%;
}
#pagination a, #pagination strong{
    list-style-type: none;
    display: inline;
    padding: 5px 8px;
    text-decoration: none; 
    background-color: inherit;
    color: #EC7117;
    font-weight: bold;
}
#pagination strong{
    color: #ffffff;
    background-color:#F00;
    background-position: top center;
    background-repeat: no-repeat;
    text-decoration: none; 
}
#pagination a:hover{
    color: #ffffff;
    background-color:#F00;
    background-position: top center;
    background-repeat: no-repeat;
    text-decoration: none; 
}

Now you can run your site. Next tutorial we will do the form validation with CI.
Download Source Code
Read more ...

How to start with Codeigniter?

Friday, February 24, 2012
If you have an experience with PHP two or three project, you should speed up your coding time with CI. CI will give you more easy life with PHP. CI uses the Model View Controller architectural pattern which gives you great flexibility when it comes to reusing, altering and upgrading code. When I write this tutorial CI version is 2.0.2. It is little different form older version. Because It support PHP 5.1.6 and newer.

Requirement

CodeIgniter

Step 1: Configuration

Download CI latest version from its official site. You will get zip file. Extract it to your sever host and rename your folder as mycisite.
Inside our mycisite folder you will found three folder and two file. You don't need to touch any folder except application folder.Open your application folder. You will see many folder and two file. Now for this step open config folder and then open config.php with your favourite editor. In line 17 you will see this code

$config['base_url'] = '';

Add your site url between single quote like following

$config['base_url'] = 'http://localhost/mycisite/';

Now you can run your site. If you run your site, you will see like following

Why? Open the mycisite>application>config>routes.php. In line 41 you will see like this

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

CI call mycisite>application>controllers>welcome.php as a default controller because of above line. We will write a home.php as default controller so change the controller name as following

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

We will also do the configuration for database. So open mycisite>application>config>database.php. From line 44 you will see like following

$db['default']['hostname'] = 'localhost';
$db['default']['username'] = '';
$db['default']['password'] = '';
$db['default']['database'] = '';
$db['default']['dbdriver'] = 'mysql';
$db['default']['dbprefix'] = '';
$db['default']['pconnect'] = TRUE;
$db['default']['db_debug'] = TRUE;
$db['default']['cache_on'] = FALSE;
$db['default']['cachedir'] = '';
$db['default']['char_set'] = 'utf8';
$db['default']['dbcollat'] = 'utf8_general_ci';
$db['default']['swap_pre'] = '';
$db['default']['autoinit'] = TRUE;
$db['default']['stricton'] = FALSE;

We need to set the hostname, username, password and database. Before you set the database, you should create a database from phpmyadmin. I create a database name as cidata. So our database setting is like that

$db['default']['hostname'] = 'localhost';
$db['default']['username'] = 'your_username';
$db['default']['password'] = 'your_password';
$db['default']['database'] = 'cidata';

Step 2:Creating our database table

The database need just one table with just 4 fields id (int 10), name (varchar 50), email (varchar 50) and message (text). Import following SQL statement via phpMyAdmin or any other MySQL tool.

CREATE TABLE `message` (
`id` int( 10 ) NOT NULL AUTO_INCREMENT ,
`name` varchar( 50 ) NOT NULL ,
`email` varchar( 50 ) NOT NULL ,
`message` text NOT NULL ,
PRIMARY KEY ( `id` )
) ENGINE = InnoDB DEFAULT CHARSET = latin1 AUTO_INCREMENT =1;

Step 3:Calling Message Form View from Controller

Now it is time to write our home.php controller. Open a new file in your editor and then copy and paste following code and save this file as mycisite>application>controllers>home.php.

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Home extends CI_Controller{

    public function __construct(){
        parent::__construct();

    }

    public function index()
    {
        echo "Hello world!";
    }
}
?>

If you run the site you will see Hello world! in your browser. It means function index is the default function for our controller. Now obviously we don't actually want it to output "Hello World!" so we can go ahead and delete that and start building it up properly. So we will call the message form as a default.

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Home extends CI_Controller{

    public function __construct(){
        parent::__construct();

    }

    public function index()
    {
        $data['base']=$this->config->item('base_url');
        $data['title']= 'Message form';
        $this->load->view('header_view',$data);
        $this->load->view('messageform_view',$data);
        $this->load->view('footer_view',$data);
    }
}
?>

We need to set the value for the $data variable array. Firstly we set our base url as a base variable. The code of $this->config->item('base_url') will grab our url data from the application>config>config.php file. Another one is the title for our form view. You can use this data in the view file as a $base or $title. So we should pay the meaningful name in our $data variable array. Then we load three view files for our message form. Why is it three? Because header and footer will include every view file. So we should do as the separate file.

Step 4: Creating Message Form View

Open a new file in your editor and let's start our header_view.php. This file is very simple for our simple project.Below is our header_view.php. Save this view file as mycisite>application>view>header_view.php.

<!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><?php echo (isset($title)) ? $title : "My CI Site" ?> </title>
<link rel="stylesheet" type="text/css" href="<?php echo $base ?>css/style.css" />
</head>
<body>
    <div id="wrapper">

You will notice that our title is called dynamically. $title variable is from our $data variable array. Behind the scenes, CI makes good use of another PHP function: extract(). This takes each value in the $data array and turns it into a new variable in its own right -so the $data array that we have just define is receive by the view as a series of separate variables: $title, $base, and so on. We use the $base variable to call the style.css file. We need to create a css folder to put our css file separately. So create a folder under the mycisite folder name as css. We don't need to write the end tag for body, html, div wrapper because we will write this end tag in our footer_view.php file. Following is our footer_view.php. Save this view file as mycisite>application>view>footer_view.php.

</div><!--<div id="wrapper">-->
</body>
</html>

It is simple, isn't it?
Now let's start our messageform_view.php. Following is our messageform_view.php. Save this view file as mycisite>application>view>messageform_view.php.

<div id="content">
<?php $this->load->helper('form'); ?>
<?php echo form_open("home/insert_message"); ?>
    <p>
        <label for="name">Name: </label>
        <input type="text" name="name" id="name" value="" size="30" />
    </p>
    <p>
        <label for="email">E-mail: </label>
        <input type="text" name="email" id="email" value="" size="30" />
    </p>
    <p>
        <label for="message">Message: </label>
        <textarea name="message" id="message" value="" cols="50" rows="4"></textarea>
    </p>
    <p>
    <input type="submit" value="Submit" />
    </p>
<?php echo form_close(); ?>
</div><!--<div id="content">-->

Firstly we need to load the form helper because we will use the CI form helper for our html form. CI has many helper for you to reduce the coding and more flexible. You can also create your own helper. If you were using plain HTML code, you'd write:
<form method="post" action="http:/www.mysite.com/index.php/websites/update" />
Whereas, if you open your form with CI, you only need to use:
form_open(home/insert_message)

If you don't understand the action link, don't worry I will explain you later.

Note incidentally, that CI assumes your forms will always send POST data rather than GET data. CI makes extensive use of the URLs itself, so this avoids confusion.

At the end of the form you need to close the form with form_close(); function. Run your site. You will see the the message form.

Step 5: Creating the insert_message function for our Controller

In our home Controller, we need to add the insert_message() function for our form submitting. Following is our home.php with insert_message() function.

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Home extends CI_Controller{

    public function __construct(){
        parent::__construct();

    }

    public function index()
    {
        $data['base']=$this->config->item('base_url');
        $data['title']= 'Message form';
        $this->load->view('header_view',$data);
        $this->load->view('messageform_view',$data);
        $this->load->view('footer_view',$data);
    }
    public function insert_message()
    {
        $this->load->model('message_model');
        $this->message_model->add_message();
    }
}
?>

Firstly we load the model message_model(next step we will create this model). And then we call the add_message() function from our message_model model.

Step 6:Creating the message_model model

It is time to create our model. Following is our message_model.php. Save this model file as mycisite>application>model>message_model.php.

<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Message_model extends CI_Model {

    public function __construct()
    {
        parent::__construct();
        $this->load->database();
    }
    public function add_message()
    {
        $data=array(
            'name'=>$_POST['name'],
            'email'=>$_POST['email'],
            'message'=>$_POST['message']
            );
        $this->db->insert('message',$data);
    }
}
?>

In our model constructor, we need to load the database library like:
$this->load->database();
CI also has many libraries. You can also learn from its user_guide inside our project folder.

Alternatively instead of loading the library in each individual model we can open autoload.php (system -> application -> config -> autoload.php) the first array we come across is the one which we want.
$autoload['libraries'] = array();
You need to put the names of each of the libraries you want in the array as single entites.
$autoload['libraries'] = array('database');
The second function is add_message() function. Remember we called the add_message() function from our controller to add our data into our database. Firstly we create the $data array. Left side is field names from our database and right side is names from our form. This line $this->db->insert('message',$data); will insert the data into our database. First parameter is our table name and second is our data. It is very to use, isn't it? Now you can run your site. If you submit the form, our data will insert into our database but our browser will be blank. So we need to redirect our site into somewhere. For this project I will redirect into our form page.

Step 7:Redirecting our page

To redirect our page, we need to call the url helper like this

$this->load->helper('url');

Now we can use redirect function like this

redirect("/home/index");

You only need to give the parameter for this function is controller name and function name. CI will do the rest. Now submit our form. You will see the form again and also fill with data into our database. Next step we will show the inserted data below the form like facebook.com.

Step 8:Creating get_all database function

To show our all message below the submit form, we need to grab all data from our database. Below function will grab the all data. Add this function to your model file.

public function get_all()
    {
        $query=$this->db->get('message');
        return $query->result();
    }

CI get() db function will grab all data from the message table. This function will return the result as an object. And then we will return the result object by using result() function. If you more prefer array form you can return array like following

return $query->result_array();

Step 9:Calling data grabbing function from our Controller

Firstly we need to load our model. And then we need to call the function that we have created already. When we call the function we need to set the return data to our data array. So following is our needed code

$this->load->model("message_model");
    $data['query']=$this->message_model->get_all();

We will add above code to the appropriate place. This place is before loading view. So our index function will be like following

public function index()
    {
        $data['base']=$this->config->item('base_url');
        $data['title']= 'Message form';
        $this->load->model("message_model");
        $data['query']=$this->message_model->get_all();
        $this->load->view('header_view',$data);
        $this->load->view('messageform_view',$data);
        $this->load->view('footer_view',$data);
    }

Step 10:Displaying message below our message form

Add the following code below your form closing function in your view.

<?php
foreach($query as $row)
{
?>
    <div>
        <?php echo $row->name; ?>: Says
    </div>

    <div>
        <?php echo $row->message; ?>
    </div>
    <br />
<?php
}
?>

This is a straight forward foreach loop looping through each of the object entities and echoing the message in our view. Now you can run your site. It will show the all message below the message form.

Step 11:Designing our site with CSS

Below is our css code for our site. Save this css file as mycisite>css>style.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:620px;
    margin:5px;
    float:left;
}
.message_form{
    width:520px;
    padding:20px 20px 0px 40px;
    border:1px dashed #A0A0A4;
}
.name_field label, .mail_field label, .message_field label{
font-weight: bold;
}
.message_field label{
    float: left;
}
.name_field{
    width:250px;
    float:left;
}
.mail_field{
    width:250px;
    float:left;
}
.message_form input[type="text"]{
    width: 170px;
}
.message_form textarea{
width: 490px;
height: 70px;
}
.message_show{
    border-bottom:1px dashed #A0A0A4;
}

Run your site. Below is my screenshot. Next tutorial we will add Pagination.

Download Source Code
Read more ...

Save Codeigniter config data in MySql database

Friday, January 27, 2012
In this tutorial, I want to show you how to save the codeigniter config data in mysql database. It means we will save config data in mysql and can grab these data when we need to use in our project and can also edit form our site dynamically.

Step 1: Configuration

For application/config/routes.php file

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

For application/config/config.php file

$config['base_url'] = 'http://localhost/ci_config/';

and

$config['enable_hooks'] = TRUE;

For application/config/autoload.php file

$autoload['libraries'] = array('database');
and
$autoload['helper'] = array('url','form');
and
$autoload['model'] = array('Siteconfig');

For application/config/database.php file

$db['default']['hostname'] = 'localhost';
$db['default']['username'] = 'root';
$db['default']['password'] = '';
$db['default']['database'] = 'ciconfig';
$db['default']['dbdriver'] = 'mysql';
$db['default']['dbprefix'] = '';

For application/config/hooks.php file

You need to add below code to your hooks.php file.
$hook['post_controller_constructor'] = array(
         'class'    => '',
         'function' => 'load_config',
         'filename' => 'my_config.php',
         'filepath' => 'hooks'
         );
You can learn more about hooks in the CI documentation here.

Setp 2: Creating Hooks file

Open new document in your favourite editor and type below code and save as application/hooks/my_config.php

<?php
  //Loads configuration from database into global CI config
  function load_config()
  {
   $CI =& get_instance();
   foreach($CI->Siteconfig->get_all()->result() as $site_config)
   {
    $CI->config->set_item($site_config->key,$site_config->value);
   }
  }
?>

We grab the config data from our database by using Siteconfig model. And set the data to global CI config. So we need to create Siteconfig model in our model folder.

Step 3:Creating database

Create a database from your MySql admin as ciconfig and run below code in your mysql tool.

CREATE TABLE IF NOT EXISTS `config_data` (
  `key` varchar(255) NOT NULL,
  `value` varchar(255) NOT NULL,
  PRIMARY KEY (`key`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `config_data`
--

INSERT INTO `config_data` (`key`, `value`) VALUES
('sitedescription', 'Tutorials for Web development and design'),
('sitename', 'TutsforWeb');

Step 4:Creating Siteconfig model

Open new document in your favourite editor and type below code and save as application/models/siteconfig.php

<?php
class Siteconfig extends CI_Model {

 public function __construct()
 {
  parent::__construct();
 }
 public function get_all()
 {
  return $this->db->get('config_data');
 }
 public function update_config($data)
 {
  $success = true;
  foreach($data as $key=>$value)
  {
   if(!$this->save($key,$value))
   {
    $success=false;
    break;  
   }
  }
  return $success;
 }
 public function save($key,$value)
 {
  $config_data=array(
    'key'=>$key,
    'value'=>$value
    );
  $this->db->where('key', $key);
  return $this->db->update('config_data',$config_data); 
 }
}

get_all() function is used in our my_config hooks file to grab all data from our database.
update_config() function is used to update our config data when the form is submitted from config view file.
save() function is called form the update_config() function to update one by one.

Step 5:Creating home Controller

Open new document in your favourite editor and type below code and save as application/controllers/home.php

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Home extends CI_Controller {
  public function index()
  {
   $this->load->view('home');
  }
  public function config()
  {
   $this->load->view('config');
  }
  public function update()
  {
   $update_data=array(
      'sitename'=>$this->input->post('sitename'),
      'sitedescription'=>$this->input->post('sitedescription')
      );
   $success = $this->Siteconfig->update_config($update_data);
   if($success) redirect("/home/index");
  }
}
?>

Step 6:Creating view files

Open new document in your favourite editor and type below code and save as application/views/home.php

<!DOCTYPE html>
<html>
  <head>
   <title><?php echo $this->config->item('sitename'); ?></title>
  </head>
<body>
  <h1><?php echo $this->config->item('sitename'); ?></h1>
  <h4><?php echo $this->config->item('sitedescription'); ?></h4>
  <a href="<?php echo base_url(); ?>index.php/home/config">Site Config</a>
</body>
</html>
As you see above code, we can use our config data by using this script <?php echo $this->config->item('sitename'); ?>

Below is the screenshot of our site.


We need to create the config view file to edit config data dynamically. Open new document in your favourite editor and type below code and save as application/views/config.php
<!DOCTYPE html>
<html>
  <head>
   <title><?php echo $this->config->item('sitename'); ?></title>
  </head>
<body>
  <h1><?php echo $this->config->item('sitename'); ?></h1>
  <h4><?php echo $this->config->item('sitedescription'); ?></h4>
  <div id="content">
  <?php echo form_open("home/update"); ?>
  <p>
   <label for="sitename">Site Name :</label>
   <input type="text" name="sitename" id="sitename" value="<?php echo $this->config->item('sitename'); ?>" size="40" />
  </p>
  <p>
   <label for="sitedescription">Site Description :</label>
   <input type="text" name="sitedescription" id="sitedescription" value="<?php echo $this->config->item('sitedescription'); ?>" size="40" /> 
  </p>
  <p>
   <input type="submit" value="Submit" />
  </p>
  <?php echo form_close(); ?>
</div>
</body>
</html>
If you click the Site Config from our home page, this page will be loaded and you can edit and update our config data.


Below is the screenshot of config view file.

Read more ...