Showing posts with label CodeIgniter. Show all posts
Showing posts with label CodeIgniter. Show all posts

CodeIgniter Tutorial: How To Login Using CodeIgniter

This video learn how to login using Codeigniter.



1- Create Database "logindb" and then create table

CREATE TABLE tbl_users (
userid tinyint(4) NOT NULL AUTO_INCREMENT,
username varchar(10) NOT NULL,
password varchar(100) NOT NULL,
PRIMARY KEY (userid)
)ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1

2- Insert New Row

INSERT INTO tbl_users(username,password) VALUES('demo',md5('test'));

3- Download Codeigniter

   - Create web directory name or web root 'loginwebsite'
   - Extract codeigniter to web root 'loginwebsite'

     application
     system
     index.php

4- Update application/config/database.php

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

5- Update $route['default_controller'] = "loginwebsite"; in application/config/routes.php

6- Update application/config/autoload.php

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

7- Update encryption_key in application/config/config.php

$config['encryption_key'] = 'APANtByIGI1BpVXZTJgcsAG8GZl8pdwwa84'

8- Create User Model in application/models/user.php

<?php
Class User extends CI_Model
{
 function login($username, $password)
 {
   $this -> db -> select('userid, username, password');
   $this -> db -> from('tbl_users');
   $this -> db -> where('username', $username);
   $this -> db -> where('password', MD5($password));
   $this -> db -> limit(1);

   $query = $this -> db -> get();

   if($query -> num_rows() == 1)
   {
     return $query->result();
   }
   else
   {
     return false;
   }
 }
}
?>

9- Create Login Controller in application/controllers/login.php

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

class Login extends CI_Controller {

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

 function index()
 {
   $this->load->helper(array('form'));
   $this->load->view('login_view');
 }

}

?>

10- Create Login View in application/views/login_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>
   <title>Simple Login with CodeIgniter</title>
 </head>
 <body>
   <h1>Simple Login with CodeIgniter</h1>

   <?php echo validation_errors(); ?>

   <?php echo form_open('verifylogin'); ?>
     <label for="username">Username:</label>
     <input type="text" size="20" id="username" name="username"/>
     <br/>
     <label for="password">Password:</label>
     <input type="password" size="20" id="passowrd" name="password"/>
     <br/>
     <input type="submit" value="Login"/>
   </form>
 </body>
</html>

11- Create VerifyLogin Controller in application/controllers/verifylogin.php

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

class VerifyLogin extends CI_Controller {

 function __construct()
 {
   parent::__construct();
   $this->load->model('user','',TRUE);
 }

 function index()
 {
   //This method will have the credentials validation
   $this->load->library('form_validation');

   $this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean');
   $this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|callback_check_database');

   if($this->form_validation->run() == FALSE)
   {
     //Field validation failed.  User redirected to login page
     $this->load->view('login_view');
   }
   else
   {
     //Go to private area
     redirect('home', 'refresh');
   }
 }

 function check_database($password)
 {
   //Field validation succeeded.  Validate against database
   $username = $this->input->post('username');

   //query the database
   $result = $this->user->login($username, $password);

   if($result)
   {
     $sess_array = array();
     foreach($result as $row)
     {
       $sess_array = array(
         'userid' => $row->userid,
         'username' => $row->username
       );
       $this->session->set_userdata('logged_in', $sess_array);
     }
     return TRUE;
   }
   else
   {
     $this->form_validation->set_message('check_database', 'Invalid username or password');
     return false;
   }
 }
}
?>

12- Create Home Controller in application/controllers/home.php

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
session_start(); //we need to call PHP's session object to access it through CI
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_view', $data);
   }
   else
   {
     //If no session, redirect to login page
     redirect('login', 'refresh');
   }
 }

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

13- Create Home View in application/views/home_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>
   <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>

14- Demo
http://localhost/loginwebsite/index.php/login

15- Source
http://downloads.ziddu.com/download/24382218/loginwebsite.zip.html

Read more blog
http://www.freeonlinelecture.com

Follow Us with Facebook
https://www.facebook.com/pages/PHP-Tutorial/782239958529506

CodeIgniter Tutorial: How To Login With Facebook Using CodeIgniter

This video learn how to login with Facebook using CodeIgniter.



Facebook.php (Save to application/config folder)

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

$config['appId']   = 'Your App ID';
$config['secret']  = 'Your App Secret';


?>

Welcome.php (Save to application/controllers folder)

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

class Welcome extends CI_Controller {

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

        // To use site_url and redirect on this controller.
        $this->load->helper('url');
}

public function login(){

$this->load->library('facebook'); // Automatically picks appId and secret from config
        // OR
        // You can pass different one like this
        //$this->load->library('facebook', array(
        //    'appId' => 'APP_ID',
        //    'secret' => 'SECRET',
        //    ));

$user = $this->facebook->getUser();
        
        if ($user) {
            try {
                $data['user_profile'] = $this->facebook->api('/me');
            } catch (FacebookApiException $e) {
                $user = null;
            }
        }else {
            $this->facebook->destroySession();
        }

        if ($user) {

            $data['logout_url'] = site_url('welcome/logout'); // Logs off application
            // OR 
            // Logs off FB!
            // $data['logout_url'] = $this->facebook->getLogoutUrl();

        } else {
            $data['login_url'] = $this->facebook->getLoginUrl(array(
                'redirect_uri' => site_url('welcome/login'), 
                'scope' => array("email") // permissions here
            ));
        }
        $this->load->view('login',$data);

}

    public function logout(){

        $this->load->library('facebook');

        // Logs off session from website
        $this->facebook->destroySession();
        // Make sure you destory website session as well.

        redirect('welcome/login');
    }

}

login.php (Save to application/views folder)


<html>

<head>
<title>Login with Facebook Using CodeIgniter</title>
</head>

<body>

<div class="container">
<form>
<!-- @user_profile check when user login successed  -->
<?php if (@$user_profile):  // call var_dump($user_profile) to view all data ?>
<!-- Display profile photo -->
<img src="https://graph.facebook.com/<?=$user_profile['id']?>/picture?type=large" style="width: 140px; height: 140px;">
<!-- Display profile name -->
<h2><?=$user_profile['name']?></h2>
<!-- Create link to facebook profile -->
<a href="<?=$user_profile['link']?>">View Profile</a>
<!-- Create link logout -->
<a href="<?= $logout_url ?>">Logout</a> 
   <!-- Display login when start home page first -->
<?php else: ?>
<h2>Login with Facebook Using CodeIgniter</h2>
<a href="<?= $login_url ?>">Login</a> 
<?php endif; ?>
</form>
</div>

</body>

</html>

libraries download from demo and then extract to application/libraries folder

Demo
http://downloads.ziddu.com/download/24375128/cfblogin.zip.html

Read more blog

CodeIgniter Tutorial: How To Update Data From Database Using CodeIgniter

This video learn how to update data from database using CodeIgniter.



1- Watch Related Video Before Start
https://www.youtube.com/watch?v=LGatnohVQK4

2- Update file autoload.php in "application/config"

Before 
$autoload['helper'] = array();

After
$autoload['helper'] = array('url', 'form', 'html');

3- Create file update_student.php for Contollers (Save to "application/controllers")

<?php

class update_student extends CI_Controller{
function __construct(){
parent::__construct();
$this->load->model('update_student_model');
}

function show_student_id() {
$id = $this->uri->segment(3);
$data['students'] = $this->update_student_model->show_students();
$data['single_student'] = $this->update_student_model->show_student_id($id);
$this->load->view('update_student', $data);
}

function update_student_id1() {
$id= $this->input->post('sid');
$data = array(
'studentid' => $this->input->post('studentid'),
'firstname' => $this->input->post('firstname'),
'lastname' => $this->input->post('lastname'),
'sex' => $this->input->post('sex')
);
$this->update_student_model->update_student_id1($id, $data);
$this->show_student_id();
redirect('student');
//echo 'You have been update this student.<br><a href=http://localhost/student/manage_student/>Go Back</a>';
}

}
?>

4- Create file update_student_model.php for Models (Save to "application/models")

<?php

class update_student_model extends CI_Model{
// Function To Fetch All Students Record
function show_students(){
$query = $this->db->get('students');
$query_result = $query->result();
return $query_result;
}

// Function To Fetch Selected Student Record
function show_student_id($data){
$this->db->select('*');
$this->db->from('students');
$this->db->where('studentid', $data);
$query = $this->db->get();
$result = $query->result();
return $result;
}

// Update Query For Selected Student
function update_student_id1($id, $data){
$this->db->where('studentid', $id);
$this->db->update('students', $data);
}
}
?>

5- Create file update_student.php for Views (Save to "application/views")

<!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>Update Students</title>
</head>
<body>
<h1>Update Data</h1>
<?php foreach ($single_student as $student): ?>
<form method="post" action="http://localhost/student/student/update_student/">
<input type="hidden" name="sid" value="<?php echo $student->studentid; ?>">
<label>Student ID :</label><br>
<input type="text" name="studentid" value="<?php echo $student->studentid; ?>"><br><br>
<label>First Name :</label><br>
<input type="text" name="firstname" value="<?php echo $student->firstname; ?>"><br><br>
<label>Last Name :</label><br>
<input type="text" name="lastname" value="<?php echo $student->lastname; ?>"><br><br>
<label>Sex :</label><br>
<input type="text" name="sex" value="<?php echo $student->sex; ?>"><br><br>
<input type="submit" id="submit" name="dsubmit" value="Update">
</form>
<?php endforeach; ?>
    <br><a href='http://localhost/student/manage_student/'>Go Back</a>

</body>
</html>

6- Add link in file manage_student.php for Views

<td>
<a href='http://localhost/student/student/show/<?php echo $studentid; ?>'>Update</a>
</td>

7- Add route code with routes.php in "application/config"

$route['student'] = "manage_student";
$route['student/show/(:any)'] = 'update_student/show_student_id/$1';
$route['student/update_student'] = 'update_student/update_student_id1';

Demo
http://downloads.ziddu.com/download/24362137/student_update.zip.html

Read more blog:
http://video-tutorial-from-youtube.blogspot.com/

Follow Us with Facebook
https://www.facebook.com/pages/PHP-Tutorial/782239958529506

CodeIgniter Tutorial: How To Delete Data From Database Using CodeIgniter

This video learn how to delete data from database using CodeIgniter.



Watch Related Video
https://www.youtube.com/watch?v=AuQ3e8qvu18

Add Function "delete_student_id" in manage_student.php (Controllers)

//This is delete function. I created function name is delete_student_id have one parameter is $studentid

function delete_student_id($studentid) {
//this function call to del_student_id method in file manage_student_model
$this->manage_student_model->del_student_id($studentid);
//This is status to show when you delete it ready
echo 'You have been delete this student.<br><a href=http://localhost/student/manage_student/>Go Back</a>';
}

Add Function "del_student_id" in manage_student_model.php (Models)

//This function is important
//function to Delete selected record from table name students

function del_student_id($studentid){
        //Where studentid=$studentid is parameter get value from controller manage_student
        $this->db->where('studentid', $studentid);
        //delete from table students and then update to database
$this->db->delete('students');   

}

Add this code to routers.php

$route['student/delete/(:any)'] = 'manage_student/delete_student_id/$1';

Demo
http://downloads.ziddu.com/download/24360486/student.zip.html

Read more blog:
http://video-tutorial-from-youtube.blogspot.com/

Follow Us with Facebook
https://www.facebook.com/pages/PHP-Tutorial/782239958529506

CodeIgniter Tutorial: How to display data from database using CodeIgniter

This video learn how to display data from database using CodeIgniter with XAMPP



1- Go codeigniter.com to download source

2- Go MyphpAdmin to create database name 'students'

3- Create table 'students'

Fields:
studentid varchar(255) Primary Key
firstname varchar(255)
lastname  varchar(255)
sex varchar(255)

4- Database Configuration in CodeIgniter

5- Update config.php in application/config

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

6- Update autoload.php in application/config

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

7- Create students.php (Save to application/controllers)

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

class Students extends CI_Controller {

public function __construct()
{
parent::__construct();
$this->load->model('Students_model');
}

public function index()
{
$this->data['students'] = $this->Students_model->get_all();
$this->load->view('students', $this->data);
}

}
?>

8- Create Students_model (Save to application/models)

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

class Students_model extends CI_Model {

public function __construct()
{
//$this->load->database();
}

function get_all() {
$this->db->select('studentid, firstname, lastname, sex');
$query = $this->db->get('students');
return $query->result_array();
}

}
?>

9- Create students.php (Save to application/views)

<!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>Display Students</title>
</head>
<body>
<div align="center">

<table border="1" cellpadding="2px" width="600px">
<tr>
<th>No.</th>
<th>First Name</th>
<th>Last Name</th>
<th>Sex</th>
</tr>
<?php
foreach ($students as $student){
 $studentid = $student['userid'];
 $firstname = $student['username'];
 $lastname = $student['password'];
 $sex = $student['sex'];
?>
    <tr>        
            <td>
            <?php echo $studentid; ?>
   </td>
            <td>
            <?php echo $firstname; ?>                          
   </td>
   <td>
            <?php echo $lastname; ?>                          
   </td>
   <td>
            <?php echo $sex; ?>                          
   </td>
</tr>        
        <?php } ?>
    </table>
</div>
</body>
</html>

10- Update routes.php in application/config

$route['default_controller'] = 'Students';
$route['student'] = "Students";

11- Create .htaccess (Save to web root)

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /student/

    #Removes access to the system folder by users.
    #Additionally this will allow you to create a System.php controller,
    #previously this would not have been possible.
    #'system' can be replaced if you have renamed your system folder.
    RewriteCond %{REQUEST_URI} ^system.*
    RewriteRule ^(.*)$ /index.php?/$1 [L]
    
    #When your application folder isn't in the system folder
    #This snippet prevents user access to the application folder
    #Submitted by: Fabdrol
    #Rename 'application' to your applications folder name.
    RewriteCond %{REQUEST_URI} ^application.*
    RewriteRule ^(.*)$ /index.php?/$1 [L]

    #Checks to see if the user is attempting to access a valid file,
    #such as an image or css document, if this isn't true it sends the
    #request to index.php
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php?/$1 [L]
</IfModule>

<IfModule !mod_rewrite.c>
    # If we don't have mod_rewrite installed, all 404's
    # can be sent to index.php, and everything works as normal.
    # Submitted by: ElliotHaughin

    ErrorDocument 404 /index.php
</IfModule>

12- Demo
http://localhost/student/

Read more blog:
http://video-tutorial-from-youtube.blogspot.com/

Follow Us with Facebook
https://www.facebook.com/pages/PHP-Tutorial/782239958529506