Home

Monday, December 31, 2012

How to configure pagination and fetch data in codeigniter?

How to configure pagination and fetch data in codeigniter.

Download this 3 Files :

Controller File : users.php
Model File       : users_model.php
View File         : userlist.php

How to Create Login Form in CodeIgniter


Step : 1

Default Libraries

In the file application/config/autoload.php you can configure the default libraries you want to load in all your controllers.  For our case, we’ll load the database and session libraries, since we want to handle user sessions, and also the URL helper for internal link generation

Before Line No : 55  $autoload['libraries'] = array();
After   Line No : 55  $autoload['libraries'] = array('database','session');

Before Line No : 67  $autoload['helper'] = array();
After   Line No : 67  $autoload['helper'] = array('url');

Encryption Key

When you use the session library, you need to set the encryption_key in the file application/config/config.php.

Before Line No : 227 $config['encryption_key'] = '';
After   Line No : 227 $config['encryption_key'] = '90b9aa7e25f80cf4f64e990b78a9fc5e';



Step : 2 Create Controller PHP file name is login.php path:(application/controllers/login.php)

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

class login extends CI_Controller
{  
    public function index()
    {
        $this->load->helper(array('form', 'url'));
        ////////  Form Validation Library Load //////////
        $this->load->library('form_validation');
       
        ///////// Session Library Load //////////////////
        $this->load->library('session');      
       
        ////////// Check Validation Form ////////////////
        $this->form_validation->set_error_delimiters('<span class="error">', '</span>');
        $this->form_validation->set_rules('username', 'username', 'required|min_length[3]|max_length[12]|trim');
        $this->form_validation->set_rules('password', 'password', 'required|min_length[2]|md5');
      
        if(!$this->form_validation->run())
        {
            $this->load->view('loginform');
        }
        else
        {          
            ///////// Database Liberary Load //////
            $this->load->database();
           
            ///////// Model Call for Login Check/////
            $this->load->model('login_model');          
           
            ///////////  Authentication Check Here //////////////////
            $result = $this->login_model->login($this->input->post('username'),$this->input->post('password'));
           
            if($result)
            {
                $sess_array = array();
                foreach($result as $row)
                {
                    $sess_array = array('id_users' => $row['id_users'],'username' => $row['username']);
                    $this->session->set_userdata('logged_in', $sess_array);
                }                                              
                redirect('home', 'refresh');
                 return TRUE;                                  
            }else
            {                          
                /////////// If Auth. is fail //////
                $data['message'] = "<font class='error'>Invalid username or password..!!</font>";                              
            }
            $this->load->view('loginform',$data);
        }        
    }  
}
?>


Step : 3 Create Model PHP file name is login_model.php  path:(application/models/login_model.php)

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

class login_model extends CI_Model { 
  
    function login($username,$password)
    {  
        $query = "SELECT * FROM ci_users WHERE username = '".$username."' AND password = '".md5($password)."' LIMIT 1";  
        $sql = $this->db->query($query);      
       
        if($sql -> num_rows() == 1)
        {
            return $sql->result_array();
        }
        else
        {
            return false;
        }          
    }
}
?>


Step : 4 Create View PHP file name is loginform.php  path:(application/views/loginform.php)

loginform.php
==>
<style>
h1{
    color:#369;
    text-align:center;
}
h3{
    color:#C39;
}
table{
    border:2px solid #0CF;
    border-radius:10px;
}
th{
    text-align:left;
}
input[type="submit"],[type="reset"]
{
    background-color:#000;
    color:#FFF;
}
 .error{
    color:#F00;
}
.success{
    color:#00F;
}
</style>

<style>
h1{
    color:#369;
    text-align:center;
}
h3{
    color:#C39;
}
table{
    border:2px solid #0CF;
    border-radius:10px;
}
th{
    text-align:left;
}
input[type="submit"],[type="reset"]
{
    background-color:#000;
    color:#FFF;
}
 .error{
    color:#F00;
}
.success{
    color:#00F;
}
</style>
<?php echo form_open('login'); ?>
       
<h1>Login Form</h1>          
<table cellpadding="10" cellspacing="10" align="center">
<?php
if(@$message)
{
    ?>
        <tR>
            <td colspan="3" align="center"><?php echo $message;?></td>
        </tR>
    <?php
}
?>
    <tR>
        <td colspan="3"><h3>Login information</h3></td>
    </tR>
    <tR>
        <th><label for="username">Username <span class="required">*</span></label></th>
        <td><input type="text" name="username" id="username" value="<?php echo set_value('username'); ?>" class="contact_textfield"/><br><span><?php echo form_error('username'); ?></span></td>                </tR>
    <tR>
        <th><label for="password">Password <span class="required">*</span></label></th>
        <td><input type="password" name="password" class="contact_textfield"/><br><span><?php echo form_error('password'); ?></span></td>                  
    </tR>
  
   <tR>
        <td colspan="2" class="height45"><input type="submit" value="Login"  class="big_btn dark"/> &nbsp; <input type="reset" value="Reset" class="big_btn dark"></td>
    </tR>
  
</table>
     
<?php echo form_close(); ?>


Step : 5 Create Controller PHP file name is home.php  path:(application/controllers/home.php)

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

class Home extends CI_Controller {

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

 function index()
 {
   if($this->session->userdata('logged_in'))
   {
     $session_data = $this->session->userdata('logged_in');
     $data['username'] = $session_data['username'];
     $this->load->view('home', $data);
   }
   else
   {
     //If no session, redirect to login page
     redirect('login', 'refresh');
   }
 }

 function logout()
 {
   $this->session->unset_userdata('logged_in');  
   redirect('home', 'refresh');
 }
}

?>

Step : 6 Create View PHP file name is home.php  path:(application/views/home.php)

home.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>
   <title>Simple Login with CodeIgniter - Private Area</title>
 </head>
 <body>
   <h1>Home</h1>
   <h2>Welcome <?php echo $username; ?>!</h2>
   <a href="home/logout">Logout</a>
 </body>
</html>



Step : 7 Run in Browser Like this http://localhost/codeIgniter/index.php/login



           

How to Create Registration Form with Mysql Database in CodeIgniter

Step : 1 First Download CodeIgniter_2.1.3c

Step :2 Create Table
          
 CREATE TABLE IF NOT EXISTS `ci_users` (
  `id_users` bigint(20) NOT NULL AUTO_INCREMENT,
  `username` varchar(255) NOT NULL,
  `password` varchar(32) NOT NULL,
  `email` varchar(255) NOT NULL,
  `artist` varchar(100) NOT NULL,
  PRIMARY KEY (`id_users`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 ;


Step : 3 Set Database Configuration path:(application/config/database.php)

$db['default']['hostname'] = 'localhost';
$db['default']['username'] = 'root';
$db['default']['password'] = '';
$db['default']['database'] = 'codeigniter';



Step : 4 Create Controller PHP file name is signup.php path:(application/controllers/signup.php)

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

class signup extends CI_Controller
{  
    public function index()
    {
        $this->load->helper(array('form', 'url'));
        ////////  Form Validation Library Load //////////
        $this->load->library('form_validation');
      
        ///////// Session Library Load //////////////////
        $this->load->library('session');      
      
        ////////// Check Validation Form ////////////////
        $this->form_validation->set_error_delimiters('<span class="error">', '</span>');
        $this->form_validation->set_rules('username', 'username', 'required|min_length[3]|max_length[12]|trim');
        $this->form_validation->set_rules('password', 'password', 'required|min_length[2]|md5');
        $this->form_validation->set_rules('email', 'email', 'required|valid_email|trim');
        $this->form_validation->set_rules('artist', 'artist', 'max_length[32]|trim'); 
       
        if(!$this->form_validation->run())
        {
            $this->load->view('signupform');
        }
        else
        {  
            ///////// Database Liberary Load //////
            $this->load->database();
          
            ///////// Model Call for Data Insert /////
            $this->load->model('signup_model');          
          
            ///////////  Username already Exists or not Check Here //////////////////
            $user_name = $this->signup_model->duplicate_usercheck($this->input->post('username'));
          
            if($user_name == 0)
            {
                ////////// Data Insert Function call //////
                $this->signup_model->signup_user();          
              
                /////////// If data is Insert then Set Success Message //////
                $data['message'] = "<font class='success'>Registration Successfully..!!</font>";
            }else
            {                          
                /////////// If Duplicate Entry in database then Set Error Message //////
                $data['message'] = "<font class='error'>Username is Allready in Database..!!</font>";              
            }
            $this->load->view('signupform',$data);          
        }       
    }   
}
?> 


Step : 5 Create Model PHP file name is signup_model.php  path:(application/models/signup_model.php)

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

class signup_model extends CI_Model {
  
    function signup_user()
    {      
        $data['username'] = $this->input->post('username');
        $data['password'] = sha1($this->input->post('password'));      
        $data['email'] = $this->input->post('email');
        $data['artist'] = $this->input->post('artist');
        $this->db->insert('ci_users', $data);
    }
  
    function duplicate_usercheck($username)
    {
         $q =  $this->db->select('username')
                   ->from('ci_users')
                   ->where(array('username' => $username))->get();
        return $q->num_rows();              
    }
}
?>


Step : 6  Create View PHP file name is signupform.php  path:(application/views/signupform.php)

signupform.php
==>
<style>
h1{
    color:#369;
    text-align:center;
}
h3{
    color:#C39;
}
table{
    border:2px solid #0CF;
    border-radius:10px;
}
th{
    text-align:left;
}
input[type="submit"],[type="reset"]
{
    background-color:#000;
    color:#FFF;
}
 .error{
    color:#F00;
}
.success{
    color:#00F;
}
</style>

<?php echo form_open('signup'); ?>
       
<h1>Registration Form</h1>           
<table cellpadding="10" cellspacing="10" align="center">
<?php
if(@$message)
{
    ?>
        <tR>
            <td colspan="3" align="center"><?php echo $message;?></td>
        </tR>
    <?php
}
?>
    <tR>
        <td colspan="3"><h3>Account information</h3></td>
    </tR>
    <tR>
        <th><label for="username">Choose a username <span class="required">*</span></label></th>
        <td><input type="text" name="username" id="username" value="<?php echo set_value('username'); ?>" class="contact_textfield"/><br><span><?php echo form_error('username'); ?></span></td>                </tR>
    <tR>
        <th><label for="password">Pick a password <span class="required">*</span></label></th>
        <td><input type="password" name="password" class="contact_textfield"/><br><span><?php echo form_error('password'); ?></span></td>                   
    </tR>
    <tR>
        <th><label for="email">Enter your valid email address <span class="required">*</span></label></th>
        <td><input type="text" name="email" id="email" value="<?php echo set_value('email'); ?>" class="contact_textfield"/><br><span><?php echo form_error('email'); ?></span></td>                </tR>
   
    <tR>
        <td colspan="3"><h3>About you</h3></td>
    </tR>
    <tR>
        <th><label for="band">Who's your favorite artist?</label></th>
        <td><input type="text" name="artist" value="<?php echo set_value('artist'); ?>" class="contact_textfield"/> <br><span><?php echo form_error('artist'); ?></span></td>                </tR>
   
   <tR>
        <td colspan="2" class="height45"><input type="submit" value="Register"  class="big_btn dark"/> &nbsp; <input type="reset" value="Reset" class="big_btn dark"></td>
    </tR>
   
</table>      
<?php echo form_close(); ?>
          




Step : 7 Run in Browser Like this http://localhost/codeIgniter/index.php/signup



           

Saturday, December 29, 2012

How can I overlay a div with semi-transparent opacity over a youtube iframe embedded video?

How can I overlay a div with semi-transparent opacity over a 
youtube iframe embedded video?
 
<iframe type="text/html"  
    src="http://www.youtube.com/embed/NWHfY_lvKIQ">
</iframe> 
 
Make sure its the first parameter in the URL. Other parameters must go after
  
Example :
<iframe type="text/html"   
  src="http://www.youtube.com/embed/NWHfY_lvKIQ?wmode=opaque">
</iframe>
 

Tuesday, December 18, 2012

How to insert data from excel into database using php

If you have Excel files that need to be imported into MySQL, you can import them easily with PHP. First, you will need to download some prerequisites:
 
Step 1 : you can use PHPExcel (download library )

Ster 2 : Create import.php file 

<?php
mysql_connect("localhost","root","");
mysql_select_db("test") or die(mysql_error());

require_once 'Classes/PHPExcel/IOFactory.php';
$objPHPExcel = PHPExcel_IOFactory::load("test.xlsx");

foreach ($objPHPExcel->getWorksheetIterator() as $worksheet)
{
    $worksheetTitle     = $worksheet->getTitle();
    $highestRow         = $worksheet->getHighestRow();
    $highestColumn      = $worksheet->getHighestColumn();
    $highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
    $nrColumns = ord($highestColumn) - 64;   
   
    for ($row = 2; $row <= $highestRow; ++ $row)
    {
        $name = $worksheet->getCellByColumnAndRow(0, $row)->getValue();      
        $age = $worksheet->getCellByColumnAndRow(1, $row)->getValue();      
        $email = $worksheet->getCellByColumnAndRow(2, $row)->getValue();          
      
        $sql_get = "INSERT INTO user (name,code,sub_dept) VALUES ('".$name."','".$age."','".$email."')";
        mysql_query($sql_get) or die(mysql_error());
    }   
}
?>

 


Wednesday, December 12, 2012

How to create a simple and efficient PHP cache

Step one: Create the top-cache.php file

<?php
$url = $_SERVER["SCRIPT_NAME"];
$break = Explode('/', $url);
$file = $break[count($break) - 1];
$cachefile = 'cached-'.substr_replace($file ,"",-4).'.html';
$cachetime = 18000;

// Serve from the cache if it is younger than $cachetime
if (file_exists($cachefile) && time() - $cachetime < filemtime($cachefile)) {
    echo "<!-- Cached copy, generated ".date('H:i', filemtime($cachefile))." -->\n";
    include($cachefile);
    exit;
}
ob_start(); // Start the output buffer
?>
 

Step two: Create the bottom-cache.php file

<?php
// Cache the contents to a file
$cached = fopen($cachefile, 'w');
fwrite($cached, ob_get_contents());
fclose($cached);
ob_end_flush(); // Send the output to the browser
?>
 

Step three: Include cache files on your page

 <?php

include('top-cache.php'); 

// Your regular PHP code goes here
echo " How to create a simple and efficient PHP cache"; 
 
include('bottom-cache.php');
?>

 

 

 

Thursday, December 6, 2012

How to Create SEO friendly URL using .htaccess

Options +FollowSymlinks
RewriteEngine on

RewriteRule ^products/([0-9]+)/([A-Za-z0-9-]+)/?$ products_details.php?pd_id=$1&prd_name=$2 [NC,L] # Handle product requests


Example : www.xyz.com/products_details.php?pd_id=51&prd_name=laptop

And you want to change them to look like this:

www.xyz.com/products/51/laptop 

rathoddhirendra.blogspot.com-Google pagerank and Worth