article

Showing posts with label Codeigniter. Show all posts
Showing posts with label Codeigniter. Show all posts

Saturday, March 22, 2014

SWFUpload in CodeIgniter

SWFUpload in CodeIgniter

First we need to integrate the library
https://code.google.com/p/swfupload/downloads/list

create a folder in the root directory of your CodeIgniter application /swf/swfupload/  

View Form
<?php echo form_open('process_form/process'); 
// Here we put the controller's URL and the function which will process the form?>
<div>
<?php
echo form_label('File:','file');
$data = array(  'id' => 'txtFileName',
'value' => '',
'size' => 50,
'disabled' => 'disabled',
'style' => 'border: solid 1px; background-color: #FFFFFF;');
echo form_input($data); //Insert the text field which will hold the file anem once it is uploaded
?>
<span id="spanButtonPlaceholder"></span>
(20 MB max)
</div>
<div id="fsUploadProgress"></div>
<input type="hidden" name="hidFileID" id="hidFileID" value="" />
<br />
<?php
$extra = 'id="btnSubmit"';
echo form_submit('upload','Send',$extra);
echo form_close();
?>
<!-- Add JavaScript files for SWFUpload -->
<script type="text/javascript" src="<?php echo base_url();?>js/swfupload/swfupload.js"></script>
<script type="text/javascript" src="<?php echo base_url();?>js/swfupload/handlers.js"></script>
<script type="text/javascript" src="<?php echo base_url();?>js/swfupload/fileprogress.js"></script>
<script type="text/javascript">
var swfu;
window.onload = function () {
swfu = new SWFUpload({
// Backend settings
upload_url: "<?php echo base_url();?>process_form/upload",
file_post_name: "resume_file",
// Flash file settings
file_size_limit : "20 MB", //File size limit
file_types : "*.jpg", // or you could use something like: "*.doc;*.wpd;*.pdf",
file_types_description : "Image Files",
file_upload_limit : 0,
file_queue_limit : 1,
// Event handler settings
swfupload_loaded_handler : swfUploadLoaded,file_dialog_start_handler: fileDialogStart,
file_queued_handler : fileQueued,
file_queue_error_handler : fileQueueError,
file_dialog_complete_handler : fileDialogComplete,
//upload_start_handler : uploadStart, // I could do some client/JavaScript validation here, but I don't need to.
swfupload_preload_handler : preLoad,
swfupload_load_failed_handler : loadFailed,
upload_progress_handler : uploadProgress,
upload_error_handler : uploadError,
upload_success_handler : uploadSuccess,
upload_complete_handler : uploadComplete,
// Button Settings
button_image_url : "<?php echo base_url();?>img/upload_flash_button_61x22.png",
button_placeholder_id : "spanButtonPlaceholder",
button_width: 61,
button_height: 22,
// Flash Settings
flash_url : "<?php echo base_url();?>swf/swfupload/swfupload.swf",
flash9_url : "<?php echo base_url();?>swf/swfupload/swfupload_fp9.swf",
custom_settings : {
progress_target : "fsUploadProgress",
upload_successful : false
},
// Debug settings
debug: false
});
};
</script>

The controller
 
<?php
class process_form extends Controller {
public function process()
{
...
//Here we take the file's name
$file_name = $this->input->post('hidFileID');
//Once we have the file's name, we could insert into the database
//or whatever is needed
...
}

public function upload()
{
$config['upload_path'] = "path/to/the/folder/for/the/file/";
 $config['allowed_types'] = 'jpg';
 $size_mb = 20; //Max file size allowed in MB
 $config['max_size'] = $size_mb * 1024; //

 $this->load->library('upload');
 $this->upload->initialize($config);
 if (!$this->upload->do_upload('resume_file'))
 {
     $this->data["params"]["error"] = array('error_upload' => $this->upload->display_errors());
     echo $this->upload->display_errors();
 }
 else
 {
     $uploaded_file = $this->upload->data();

     //Return to the form the final name of the file once it was uploaded
     echo $uploaded_file["file_name"];
 }
}
}

Friday, August 23, 2013

CodeIgniter Search Query Strings

CodeIgniter Search Query Strings

Create Database table film_list
CREATE TABLE IF NOT EXISTS `film_list` (
  `FID` int(11) NOT NULL AUTO_INCREMENT,
  `title` varchar(255) NOT NULL,
  `category` varchar(255) NOT NULL,
  `length` varchar(255) NOT NULL,
  `rating` varchar(255) NOT NULL,
  `price` varchar(255) NOT NULL,
  PRIMARY KEY (`FID`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=9 ;
Insert data
INSERT INTO `film_list` (`FID`, `title`, `category`, `length`, `rating`, `price`) VALUES
(1, 'Final Fantasy', 'Animation', '1:30', 'G', '2.0'),
(2, 'My Sassy Girl', 'Love Story', '1:40', 'G', '2.3'),
(3, 'The Shawshank Redemption', 'Horror', '1:40', 'PG', '3'),
(4, 'The Godfather', 'Drama', '1:60', 'G', '1.3'),
(5, 'Star Wars ', 'Animation', '2:10', 'G', '2'),
(6, 'Shichinin no samurai ', 'Action', '1:10', 'G', '2'),
(7, 'The Matrix', 'Action', '1:25', 'G', '1'),
(8, 'The Lord of the Rings: The Two Towers', 'Action', '2.60', 'G', '2');

Create Table Category
CREATE TABLE IF NOT EXISTS `category` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=9 ;

Insert data category
INSERT INTO `category` (`id`, `name`) VALUES
(1, 'Action'),
(2, 'Animation'),
(3, 'Children'),
(4, 'Comedy'),
(5, 'Drama'),
(6, 'Horror'),
(7, 'Love Story'),
(8, 'Sports');

Create table 
CREATE TABLE IF NOT EXISTS `ci_query` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `query_string` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=19 ;

Setup base_url
application\config\config.php
$config['base_url']    = 'http://localhost/DEVELOPMENT/CODEIGNATER/';

Create Controller 
application\controllers\films.php

<?php
class Films extends CI_Controller{
 function __construct() {
        parent:: __construct();
        $this->load->helper("url");
  $this->load->model('Film_model');
  $this->load->helper(array('form', 'url'));
    }
 function display($query_id = 0, $sort_by = 'title', $sort_order = 'asc', $offset = 0) {
  $limit = 5;
  $data['fields'] = array(
   'FID' => 'ID',
   'title' => 'Title',
   'category' => 'Category',
   'length' => 'Length',
   'rating' => 'Rating',
   'price' => 'Price'
  );
  
  $this->input->load_query($query_id);
  
  $query_array = array(
   'title' => $this->input->get('title'),
   'category' => $this->input->get('category'),
   'length_comparison' => $this->input->get('length_comparison'),
   'length' => $this->input->get('length'),
  );
  
  $data['query_id'] = $query_id;
  
  $this->load->model('Film_model');
  
  $results = $this->Film_model->search($query_array, $limit, $offset, $sort_by, $sort_order);
  
  $data['films'] = $results['rows'];
  $data['num_results'] = $results['num_rows'];
  
  // pagination
  $this->load->library('pagination');
  $config = array();
  $config['base_url'] = site_url("films/display/$query_id/$sort_by/$sort_order");
  $config['total_rows'] = $data['num_results'];
  $config['per_page'] = $limit;
  $config['uri_segment'] = 6;
  $this->pagination->initialize($config);
  $data['pagination'] = $this->pagination->create_links();
  
  $data['sort_by'] = $sort_by;
  $data['sort_order'] = $sort_order;
  
  $data['category_options'] = $this->Film_model->category_options();
  
  $this->load->view('films', $data);
 }
 function search() {
  $query_array = array(
   'title' => $this->input->post('title'),
   'category' => $this->input->post('category'),
   'length_comparison' => $this->input->post('length_comparison'),
   'length' => $this->input->post('length'),
  );
  
  $query_id = $this->input->save_query($query_array);
  
  redirect("films/display/$query_id");
 }
}
Create Models
application\models\Film_model.php
<?php
class Film_model extends CI_Model {
 function search($query_array, $limit, $offset, $sort_by, $sort_order) {
  $sort_order = ($sort_order == 'desc') ? 'desc' : 'asc';
  $sort_columns = array('FID', 'title', 'category', 'length', 'rating', 'price');
  $sort_by = (in_array($sort_by, $sort_columns)) ? $sort_by : 'title';
  
  // results query
  $q = $this->db->select('FID, title, category, length, rating, price')
   ->from('film_list')
   ->limit($limit, $offset)
   ->order_by($sort_by, $sort_order);
  
  if (strlen($query_array['title'])) {
   $q->like('title', $query_array['title']);
  }
  if (strlen($query_array['category'])) {
   $q->where('category', $query_array['category']);
  }
  if (strlen($query_array['length'])) {
   $operators = array('gt' => '>', 'gte' => '>=', 'eq' => '=', 'lte' => '<=', 'lt' => '<');
   $operator = $operators[$query_array['length_comparison']];
      
   $q->where("length $operator", $query_array['length']);
  }
  
  $ret['rows'] = $q->get()->result();
  
  // count query
  $q = $this->db->select('COUNT(*) as count', FALSE)
   ->from('film_list');
  
  if (strlen($query_array['title'])) {
   $q->like('title', $query_array['title']);
  }
  if (strlen($query_array['category'])) {
   $q->where('category', $query_array['category']);
  }
  if (strlen($query_array['length'])) {
   $operators = array('gt' => '>', 'gte' => '>=', 'eq' => '=', 'lte' => '<=', 'lt' => '<');
   $operator = $operators[$query_array['length_comparison']];
      
   $q->where("length $operator", $query_array['length']);
  }
  
  $tmp = $q->get()->result();
  
  $ret['num_rows'] = $tmp[0]->count;
  
  return $ret;
 }
 function category_options() {
  $rows = $this->db->select('name')
   ->from('category')
   ->get()->result();
  $category_options = array('' => '');
  foreach ($rows as $row) {
   $category_options[$row->name] = $row->name;
  }
  return $category_options;
 }
}
Create View
application\views\films.php
<html lang="en-US">
<head>
 <title>Films</title>
 <meta charset="UTF-8">
 <style>
  * {
   font-family: Arial;
   font-size: 12px;
  }
  table {
   border-collapse: collapse;
  }
  td, th {
   border: 1px solid #666666;
   padding:  4px;
  }
  div {
   margin: 4px;
  }
  .sort_asc:after {
   content: "▲";
  }
  .sort_desc:after {
   content: "▼";
  }
  label {
   display: inline-block;
   width: 120px;
  }
 </style>
</head>
<body>
 <?php echo form_open('films/search'); ?>
  <div>
   <?php echo form_label('Title:', 'title'); ?>
   <?php echo form_input('title', set_value('title'), 'id="title"'); ?>
  </div>
  <div>
   <?php echo form_label('Category:', 'category'); ?>
   <?php echo form_dropdown('category', $category_options, 
    set_value('category'), 'id="category"'); ?>
  </div>
  <div>
   <?php echo form_label('Length:', 'length'); ?>
   <?php echo form_dropdown('length_comparison', 
    array('gt' => '>', 'gte' => '>=', 'eq' => '=', 'lte' => '<=', 'lt' => '<') , 
    set_value('length_comparison'), 'id="length_comparison"'); ?>
   <?php echo form_input('length', set_value('length'), 'id="length"'); ?>
  </div>
  <div>
   <?php echo form_submit('action', 'Search'); ?>
  </div>
 <?php echo form_close(); ?>
 <div>
  Found <?php echo $num_results; ?> films
 </div>
 <table>
  <thead>
   <?php foreach($fields as $field_name => $field_display): ?>
   <th <?php if ($sort_by == $field_name) echo "class=\"sort_$sort_order\"" ?>>
    <?php echo anchor("films/display/$query_id/$field_name/" .
     (($sort_order == 'asc' && $sort_by == $field_name) ? 'desc' : 'asc') ,
     $field_display); ?>
   </th>
   <?php endforeach; ?>
  </thead>
  
  <tbody>
   <?php foreach($films as $film): ?>
   <tr>
    <?php foreach($fields as $field_name => $field_display): ?>
    <td>
     <?php echo $film->$field_name; ?>
    </td>
    <?php endforeach; ?>
   </tr>
   <?php endforeach; ?>   
  </tbody>
  
 </table>
 
 <?php if (strlen($pagination)): ?>
 <div>
  Pages: <?php echo $pagination; ?>
 </div>
 <?php endif; ?>
</body>
</html>
Create file My_Input.php
application\core\My_Input.php
<?php
class MY_Input extends CI_Input {
 function save_query($query_array) {
  $CI =& get_instance();
  $CI->db->insert('ci_query', array('query_string' => http_build_query($query_array)));
  return $CI->db->insert_id();
 }
 function load_query($query_id) {
  $CI =& get_instance();
  $rows = $CI->db->get_where('ci_query', array('id' => $query_id))->result();
  if (isset($rows[0])) {
   parse_str($rows[0]->query_string, $_GET);  
  }
 }
}
View
http://localhost/CODEIGNATER/films/display/

Login Register using codeigniter

Login Register using codeigniter

Create database table 
CREATE TABLE IF NOT EXISTS `membership` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `first_name` varchar(255) NOT NULL,
  `last_name` varchar(255) NOT NULL,
  `email_address` varchar(255) NOT NULL,
  `username` varchar(255) NOT NULL,
  `password` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;

Setup base_url
application\config\config.php
$config['base_url']    = 'http://localhost/CODEIGNATER/';

setup routes
application\config\routes.php
$route['default_controller'] = "login_register";

Create Controller
application\controllers\login_register.php

<?php
class Login_register extends CI_Controller{
 function __construct()
  {
   parent::__construct();
    $this->load->helper(array('form', 'url'));
  }
 function index($msg = NULL)
 {
  $data['msg'] = $msg;
  $data['main_content'] = 'login_form';
  $this->load->view('includes/template', $data); 
  
  
 } 
 function validate_credentials()
 {  
  $this->load->model('membership_model');
  $query = $this->membership_model->validate();
  
  if($query) // if the user's credentials validated...
  {
   $data = array(
    'username' => $this->input->post('username'),
    'is_logged_in' => true
   );
   $this->session->set_userdata($data);
   redirect('Login_register/logged_in_area');
  }
  else // incorrect username or password
  {
   $msg = '<p class=error>Invalid username and/or password.</p>';
            $this->index($msg);
  }
 } 
 
 function signup()
 {
  $data['main_content'] = 'signup_form';
  $this->load->view('includes/template', $data);
 }
 function logged_in_area()
 {
  $data['main_content'] = 'logged_in_area';
  $this->load->view('includes/template', $data);
 }
 
 function create_member()
 {
  $this->load->library('form_validation');
  
  // field name, error message, validation rules
  $this->form_validation->set_rules('first_name', 'Name', 'trim|required');
  $this->form_validation->set_rules('last_name', 'Last Name', 'trim|required');
  $this->form_validation->set_rules('email_address', 'Email Address', 'trim|required|valid_email');
  $this->form_validation->set_rules('username', 'Username', 'trim|required|min_length[4]');
  $this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[4]|max_length[32]');
  $this->form_validation->set_rules('password2', 'Password Confirmation', 'trim|required|matches[password]');
  
  
  if($this->form_validation->run() == FALSE)
  {
   $this->load->view('signup_form');
  }
  
  else
  {   
   $this->load->model('membership_model');
   
   if($query = $this->membership_model->create_member())
   {
    $data['main_content'] = 'signup_successful';
    $this->load->view('includes/template', $data);
   }
   else
   {
    $this->load->view('signup_form');   
   }
  }
  
 }
 
 function logout()
 {
  $this->session->sess_destroy();
  $this->index();
 }

}
Create Modal
application\models\membership_model.php
<?php
class Membership_model extends CI_Model {
 function validate()
 {
  $this->db->where('username', $this->input->post('username'));
  $this->db->where('password', md5($this->input->post('password')));
  $query = $this->db->get('membership');
  
  if($query->num_rows == 1)
  {
   return true;
  }
  
 }
 function create_member()
 {
  $new_member_insert_data = array(
   'first_name' => $this->input->post('first_name'),
   'last_name' => $this->input->post('last_name'),
   'email_address' => $this->input->post('email_address'),   
   'username' => $this->input->post('username'),
   'password' => md5($this->input->post('password'))      
  );
  
  $insert = $this->db->insert('membership', $new_member_insert_data);
  return $insert;
 }
}
Create View
application\views\login_form.php
<?php $this->load->view('includes/header'); ?>
<div id="login_form">
 <h1>Login</h1>
 <?php if(! is_null($msg)) echo $msg;?>  
    <?php 
 echo form_open('Login_register/validate_credentials');
 echo form_input('username', 'Username');
 echo form_password('password', 'Password');
 echo form_submit('submit', 'Login');
 echo anchor('Login_register/signup', 'Create Account','style=padding-left:10px;');
 echo form_close();
 ?>
</div>
<?php $this->load->view('includes/tutorial_info'); ?>
<?php $this->load->view('includes/footer'); ?>
Create View
application\views\includes\header.php
<html lang="en">
<head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> 
 <title>Sign Up!</title>
 <link rel="stylesheet" href="<?php echo base_url();?>/css/style.css" type="text/css" media="screen" />
</head>
<body>
Create View
application\views\includes\tutorial_info.php
<div>created by <a href="http://tutorial101.blogspot.com/">http://tutorial101.blogspot.com/</a></div>
Create View
application\views\includes\template.php
<?php $this->load->view('includes/header'); ?>
<?php $this->load->view($main_content); ?>
<?php $this->load->view('includes/footer'); ?>
Create View
application\views\includes\footer.php
 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript" charset="utf-8"></script> 
 <script type="text/javascript" charset="utf-8">
  $('input').click(function(){
   $(this).select(); 
  });
 </script>
</body>
</html>
Create View
application\views\signup_form.php
<?php $this->load->view('includes/header'); ?>
<h1>Create an Account!</h1>
<fieldset>
<legend>Personal Information</legend>
<?php
echo form_open('Login_register/create_member');
echo form_input('first_name', set_value('first_name', 'First Name'));
echo form_input('last_name', set_value('last_name', 'Last Name'));
echo form_input('email_address', set_value('email_address', 'Email Address'));
?>
</fieldset>

<fieldset>
<legend>Login Info</legend>
<?php
echo form_input('username', set_value('username', 'Username'));
echo form_input('password', set_value('password', 'Password'));
echo form_input('password2', 'Password Confirm');

echo form_submit('submit', 'Create Acccount');
?>
<?php echo validation_errors('<p class="error">'); ?>
</fieldset>
<?php $this->load->view('includes/tutorial_info'); ?>
<?php $this->load->view('includes/footer'); ?>
Create View
application\views\signup_successful.php
<h1>Congrats!</h1>
<p>Your account has not been created. <?php echo anchor('Login_register', 'Login Now');?></p>
Create View
application\views\logged_in_area.php
<html lang="en">
<head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> 
 <title>Login Regsiter codeigniter</title>
</head>
<body>
 <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('Login_register/logout', 'Logout'); ?></h4>
</body>
</html> 
Create folder name css root directory
css\style.css
body {
 background: #b6b6b6;
 margin: 0;
 padding: 0;
 font-family: arial;
}

#login_form {
 width: 300px;
 margin: 10px auto 0;
 padding: 1em;
 border-radius: 5px; -webkit-border-radius: 5px; -moz-border-radius: 5px;
 background-color: #EBF8D6;
 border: 1px solid #A6DD88;
 color: #539B2D;
}
h1,h2,h3,h4,h5 {
 margin-top: 0;
 font-family:Arial, Lucida Grande, Verdana, Sans-serif;font-size:22px;color:#000;
 text-align: center;
}
input[type=text], input[type=password] {
 display: block;
 margin: 0 0 1em 0;
 width: 280px;
 border: 5px;
 -moz-border-radius: 1px;
 -webkit-border-radius: 1px;
 padding: 1em;
 border: 1px solid #CCCCCC;
}
input[type=submit] {
 border:1px outset #ccc;padding:5px 2px 4px;color:#fff;min-width: 100px;text-align: center;cursor:pointer;background:#729e01;background:-webkit-gradient(linear, left top, left bottom,from(#a3d030),to(#729e01));background:-moz-linear-gradient(top,#a3d030,#729e01);background:-o-linear-gradient(top,#a3d030,#729e01);background:linear-gradient(top,#a3d030,#729e01);-moz-border-radius:7px; -webkit-border-radius:7px;
}
input[type=submit]:hover {
 background: #6B8426;
 cursor: pointer;
}
/* Validation error messages */
.error {
 background-color: #FFECE6;
 border: 1px solid #FF936F;
 color: #842100;
 background-image: url(../img/delete00.png);
 
 background-repeat: no-repeat;
 background-position: 10px center;
 height: 20px;
 text-transform: uppercase;
 font-size: 11px;
 line-height: 22px;
 margin-bottom: 20px;
 padding-top: 10px;
 padding-right: 10px;
 padding-bottom: 10px;
 padding-left: 50px;
}

fieldset {
 width: 300px;
 margin: auto;
 margin-bottom: 2em;
 display: block;
}
create folder name img root directory View http://localhost/CODEIGNATER/Login_register/

Download http://bit.ly/2DF6FJP

Wednesday, August 21, 2013

Build ajax data grids with codeigniter and jquery

Build ajax data grids with codeigniter and jquery

Create database table
CREATE TABLE IF NOT EXISTS `users_01` (
  `user_id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(20) DEFAULT NULL,
  `password` varchar(20) DEFAULT NULL,
  `user_type` enum('regular','admin') NOT NULL DEFAULT 'regular',
  `email` varchar(255) NOT NULL,
  PRIMARY KEY (`user_id`),
  UNIQUE KEY `username` (`username`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=72 ;

setup baseurl
application\config\config.php
$config['base_url']    = 'http://localhost/codeigniter/';

setup route
application\config\routes.php
$route['default_controller'] = "test";

Create Controller

//application\controllers\test.php
<?php
//application\controllers\test.php
class Test extends CI_Controller{
 function __construct(){
  parent::__construct();
  $this->load->helper(array('datagrid','url'));
  $this->Datagrid = new Datagrid('users_01','user_id');
 }
 
 function index(){
  $this->load->helper('form');
  $this->load->library('session');
  $this->load->view('users');
 }
 
 function proc($request_type = ''){
  $this->load->helper('url');
  if($action = Datagrid::getPostAction()){
   $error = "";
   switch($action){
    case 'delete' :
     if(!$this->Datagrid->deletePostSelection()){
      $error = 'Items could not be deleted';
     }
    break;
   }
   if($request_type!='ajax'){
    $this->load->library('session');
    $this->session->set_flashdata('form_error',$error);
    redirect('test/index');
   } else {
    echo json_encode(array('error' => $error));
   }
  } else {
   die("Bad Request");
  }
 }
}
?>
Create View
//application\views\user.php
<html>
<head>
 <title>Users Management</title>
 <script src="<?php echo base_url(); ?>js/jquery-1.6.3.min.js"></script>
 <script src="<?php echo base_url(); ?>js/datagrid.js"></script>
</head>
<body>
<style>
 .dg_form table{
  border:1px solid silver;
 }
 
 .dg_form th{
  background-color:gray;
  font-family:"Courier New", Courier, mono;
  font-size:12px;
 }
 
 .dg_form td{
  background-color:gainsboro;
  font-size:12px;
 }
 
 .dg_form input[type=submit]{
  margin-top:2px;
 }
</style>
<?php
  $this->Datagrid->hidePkCol(true);
  $this->Datagrid->setHeadings(array('email'=>'E-mail'));
  $this->Datagrid->ignoreFields(array('password'));
  if($error = $this->session->flashdata('form_error')){
   echo "<font color=red>$error</font>";
  }
  echo form_open('test/proc',array('class'=>'dg_form'));
  echo $this->Datagrid->generate();
  echo Datagrid::createButton('delete','Delete');
  echo form_close();
?>
</body>
</html>
Create javascript root directory js folder
//js/datagrid.js
$(function(){
   $('.dg_form :submit').click(function(e){
    e.preventDefault();
    var $form = $(this).parents('form');
    var action_name = $(this).attr('class').replace("dg_action_","");
    var action_control = $('<input type="hidden" name="dg_action['+action_name+']" value=1 />');
    
    $form.append(action_control);
    
    var post_data = $form.serialize();
    action_control.remove();
    
    var script = $form.attr('action')+'/ajax';
    $.post(script, post_data, function(resp){
     if(resp.error){
      alert(resp.error);
     } else {
      switch(action_name){
       case 'delete' :
        // remove deleted rows from the grid
        $form.find('.dg_check_item:checked').parents('tr').remove();
       break;
       case 'anotherAction' :
        // do something else...
       break;
      }
     }
    })
   })
   
   $('.dg_check_toggler').click(function(){
    var checkboxes = $(this).parents('table').find('.dg_check_item');
    if($(this).is(':checked')){
     checkboxes.attr('checked','true');
    } else {
     checkboxes.removeAttr('checked');
    }
   })
   
   
  })

CodeIgniter Shopping Cart

CodeIgniter Shopping Cart

Create Database table

CREATE TABLE IF NOT EXISTS `products` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `qty` int(11) NOT NULL,
  `price` int(11) NOT NULL,
  `name` varchar(255) NOT NULL,
  `image` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;

INSERT INTO `products` (`id`, `qty`, `price`, `name`, `image`) VALUES
(1, 10, 500, 'Samsung Galaxy S 2', 'galaxys2.jpg'),
(2, 20, 600, 'Samsung Galaxy S 3', 'galaxys3.jpg');

Setup baseurl application\config\config.php
$config['base_url'] = "http://localhost/codeignater/";

Set route application\config\routes.php
$route['default_controller'] = "cart";

Create Controller
//application/controllers/cart.php
<?php
class Cart extends Controller { 

 function Cart()
 {
  parent::Controller(); // We define the the Controller class is the parent. 
  $this->load->model('cart_model'); // Load our cart model for our entire class
 }
 
 function index()
 {
  $data['products'] = $this->cart_model->retrieve_products(); // Retrieve an array with all products
  
  $data['content'] = 'cart/products'; // Select view to display
  $this->load->view('index', $data); // Display the page
 }
 
 function add_cart_item(){
  
  if($this->cart_model->validate_add_cart_item() == TRUE){
   
   // Check if user has javascript enabled
   if($this->input->post('ajax') != '1'){
    redirect('cart'); // If javascript is not enabled, reload the page with new data
   }else{
    echo 'true'; // If javascript is enabled, return true, so the cart gets updated
   }
  }
  
 }
 
 function update_cart(){
  $this->cart_model->validate_update_cart();
  redirect('cart');
 }
 
 function show_cart(){
  $this->load->view('cart/cart');
 }
 
 function empty_cart(){
  $this->cart->destroy();
  redirect('cart');
 }
}
Create Model
///application/models/cart_model.php
<?php 
class Cart_model extends Model {

 // Function to retrieve an array with all product information
 function retrieve_products(){
  $query = $this->db->get('products');
  return $query->result_array();
 }
 
 // Updated the shopping cart
 function validate_update_cart(){
  
  // Get the total number of items in cart
  $total = $this->cart->total_items();
  
  // Retrieve the posted information
  $item = $this->input->post('rowid');
     $qty = $this->input->post('qty');

  // Cycle true all items and update them
  for($i=0;$i < $total;$i++)
  {
   // Create an array with the products rowid's and quantities. 
   $data = array(
               'rowid' => $item[$i],
               'qty'   => $qty[$i]
            );
            
            // Update the cart with the new information
   $this->cart->update($data);
  }

 }
 
 // Add an item to the cart
 function validate_add_cart_item(){
  
  $id = $this->input->post('product_id'); // Assign posted product_id to $id
  $cty = $this->input->post('quantity'); // Assign posted quantity to $cty
  
  $this->db->where('id', $id); // Select where id matches the posted id
  $query = $this->db->get('products', 1); // Select the products where a match is found and limit the query by 1
  
  // Check if a row has been found
  if($query->num_rows > 0){
  
   foreach ($query->result() as $row)
   {
       $data = array(
                 'id'      => $id,
                 'qty'     => $cty,
                 'price'   => $row->price,
                 'name'    => $row->name
             );

    $this->cart->insert($data); 
    
    return TRUE;
   }
  
  // Nothing found! Return FALSE! 
  }else{
   return FALSE;
  }
 }
}
Create view index
//application\views\index.php
<html>
<head>
<title>CodeIgniter Shopping Cart</title>
<link href="<?php echo base_url(); ?>assets/css/core.css" media="screen" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="<?php echo base_url(); ?>assets/js/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="<?php echo base_url(); ?>assets/js/core.js"></script>
</head>
<body>
<div id="wrap">
 <?php $this->view($content); ?>
 <div class="cart_list">
  <h3>Your shopping cart</h3>
  <div id="cart_content">
   <?php echo $this->view('cart/cart.php'); ?>
  </div>
 </div>
</div>
</body>
</html>
Create view cart.php
//application\views\cart\cart.php
<?php if(!$this->cart->contents()):
 echo 'You don\'t have any items yet.';
else:
?>

<?php echo form_open('cart/update_cart'); ?>
<table width="100%" cellpadding="0" cellspacing="0">
 <thead>
  <tr>
   <td>Qty</td>
   <td>Item Description</td>
   <td>Item Price</td>
   <td>Sub-Total</td>
  </tr>
 </thead>
 <tbody>
  <?php $i = 1; ?>
  <?php foreach($this->cart->contents() as $items): ?>
  
  <?php echo form_hidden('rowid[]', $items['rowid']); ?>
  <tr <?php if($i&1){ echo 'class="alt"'; }?>>
     <td>
      <?php echo form_input(array('name' => 'qty[]', 'value' => $items['qty'], 'maxlength' => '3', 'size' => '5')); ?>
     </td>
     
     <td><?php echo $items['name']; ?></td>
     
     <td>$<?php echo $this->cart->format_number($items['price']); ?></td>
     <td>$<?php echo $this->cart->format_number($items['subtotal']); ?></td>
    </tr>
    
    <?php $i++; ?>
  <?php endforeach; ?>
  
  <tr>
   <td</td>
     <td></td>
     <td><strong>Total</strong></td>
     <td>$<?php echo $this->cart->format_number($this->cart->total()); ?></td>
  </tr>
 </tbody>
</table>

<p><?php echo form_submit('', 'Update your Cart'); echo anchor('cart/empty_cart', 'Empty Cart', 'class="empty"');?></p>
<p><small>If the quantity is set to zero, the item will be removed from the cart.</small></p>
<?php 
echo form_close(); 
endif;
?>
Create View Product.php
//application\views\cart\products.php
<ul class="products">
 <?php foreach($products as $p): ?>
 <li>
  <h3><?php echo $p['name']; ?></h3>
  <img src="<?php echo base_url(); ?>assets/img/products/<?php echo $p['image']; ?>" alt="" />
  <small>$<?php echo $p['price']; ?></small>
  <?php echo form_open('cart/add_cart_item'); ?>
   <fieldset>
    <label>Quantity</label>
    <?php echo form_input('quantity', '1', 'maxlength="2"'); ?>
    <?php echo form_hidden('product_id', $p['id']); ?>
    <?php echo form_submit('add', 'Add'); ?>
   </fieldset>
  <?php echo form_close(); ?>
 </li>
 <?php endforeach;?>
</ul>
Create CSS core.css in root directory assets\css\core.css
body{
 font-family: "Lucida Sans";
 font-size: 12px;
}

#wrap{
 width: 1024px;
}

ul.products{
 list-style-type: none;
 width: 525px;
 margin: 0;
 padding: 0;
}

 ul.products li{
  background: #eeeeee;
  border: 1px solid #d3d3d3;
  padding: 5px;
  width: 150px;
  text-align: center;
  float: left;
  margin-right: 10px;
 }

 ul.products h3{
  margin: 0;
  padding: 0px 0px 5px 0px;
  font-size: 14px;
 }
 
 ul.products small{
  display: block;
 }
 
 ul.products form fieldset{
  border: 0px;
 }
 
 ul.products form label{
  font-size: 12px;
 }
 
 ul.products form input[type=text]{
  width: 18px;
  background: #FFF;
  border: 1px solid #d3d3d3;
 }
div.cart_list{
 background: #eeeeee;
 border: 1px solid #d3d3d3;
 padding: 5px;
 float: left; 
 width: 490px;
}

 div.cart_list h3{
  margin: 0 0 10px 0;
  padding: 0;
  font-size: 14px;
 }
 
 div.cart_list table thead tr td{
  border-bottom: 1px solid #d3d3d3;
  padding: 5px;
 }
 
 div.cart_list table tbody tr td{
  padding: 5px;
 }
 
 div.cart_list table tbody tr td input[type=text]{
  background: #FFF;
  border: 1px solid #d3d3d3;
  width: 25px;
 }
 
 div.cart_list table tbody tr.alt{
  background: #f5f5f5;
 }
Create folder for image root directory assets\img\products\galaxys2.jpg, assets\img\products\galaxys3.jpg Create javascript file assets\js\core.js
$(document).ready(function() { 
 /*place jQuery actions here*/ 
 var link = "/codeignater/index.php/";
 
 
 $("ul.products form").submit(function() {
  // Get the product ID and the quantity 
  var id = $(this).find('input[name=product_id]').val();
  var qty = $(this).find('input[name=quantity]').val();
  
   $.post(link + "cart/add_cart_item", { product_id: id, quantity: qty, ajax: '1' },
     function(data){
     
     if(data == 'true'){
       
       $.get(link + "cart/show_cart", function(cart){
       $("#cart_content").html(cart);
    });

      }else{
       alert("Product does not exist");
      } 
      
    }); 

  return false;
 });
 
 $(".empty").live("click", function(){
     $.get(link + "cart/empty_cart", function(){
      $.get(link + "cart/show_cart", function(cart){
      $("#cart_content").html(cart);
   });
  });
  
  return false;
    });

});

Wednesday, August 7, 2013

Codeigniter Add, Edit, Delete, jquery ajax, jquery-ui

Codeigniter Add, Edit, Delete, jquery ajax, jquery-ui

Create Database Table
CREATE TABLE IF NOT EXISTS `daily` (
  `id` int(5) NOT NULL AUTO_INCREMENT,
  `date` date NOT NULL,
  `name` varchar(64) NOT NULL,
  `amount` double NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=10 ;

Create Controllerapplication\controllers\daily.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Daily extends CI_Controller {
  public function __construct() {
        parent:: __construct();
        $this->load->helper("url");
        $this->load->model('MDaily');
  $this->load->helper('form');
    }
 
  public function index(){
    $data['query'] = $this->MDaily->getAll();
    $this->load->view('daily/input',$data);
  }
 
  public function submit(){
    if ($this->input->post('ajax')){
      if ($this->input->post('id')){
        $this->MDaily->update();
        $data['query'] = $this->MDaily->getAll();
        $this->load->view('daily/show',$data);
      }else{
        $this->MDaily->save();
        $data['query'] = $this->MDaily->getAll();
        $this->load->view('daily/show',$data);
      }
    }
  }
 
  public function delete(){
    $id = $this->input->post('id');
    $this->db->delete('daily', array('id' => $id));
    $data['query'] = $this->MDaily->getAll();
    $this->load->view('daily/show',$data);
  }
}
Create Modalapplication\models\MDaily.php
<?php
class MDaily extends CI_Model {
  function getAll(){
    $this->db->select('*');
    $this->db->from('daily');
    $this->db->limit(50);
    $this->db->order_by('id','ASC');
    $query = $this->db->get();
 
    return $query->result();
  }
 
  function get($id){
    $query = $this->db->getwhere('daily',array('id'=>$id));
    return $query->row_array();
  }
 
  function save(){
    $date = $this->input->post('date');
    $name = $this->input->post('name');
    $amount=$this->input->post('amount');
    $data = array(
      'date'=>$date,
      'name'=>$name,
      'amount'=>$amount
    );
    $this->db->insert('daily',$data);
  }
 
  function update(){
    $id   = $this->input->post('id');
    $date = $this->input->post('date');
    $name = $this->input->post('name');
    $amount=$this->input->post('amount');
    $data = array(
      'date'=>$date,
      'name'=>$name,
      'amount'=>$amount
    );
    $this->db->where('id',$id);
    $this->db->update('daily',$data);
  }
 
}
Create Viewapplication\views\daily\input.php
<html lang="en-US">
  <head>
    <title>Daily Notes</title>
    <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.6/themes/base/jquery-ui.css" type="text/css" media="all" />
    <link rel="stylesheet" href="http://static.jquery.com/ui/css/demo-docs-theme/ui.theme.css" type="text/css" media="all" />
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js" type="text/javascript"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.6/jquery-ui.min.js" type="text/javascript"></script>
    <script src="http://jquery-ui.googlecode.com/svn/tags/latest/external/jquery.bgiframe-2.1.2.js" type="text/javascript"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.6/i18n/jquery-ui-i18n.min.js" type="text/javascript"></script>
    <meta charset="UTF-8">
    <style>
        body { font-size: 75%; }
        label, input { display:block; }
        input.text { margin-bottom:12px; width:95%; padding: .4em; }
        h1 { font-size: 1.2em; margin: .6em 0; }
        a{text-decoration:none;}
        {font-size:60%};
    </style>
    <script>
    $(function() {
 
        $( "#dialog:ui-dialog" ).dialog( "destroy" );
 
        $( "#dialog-confirm" ).dialog({
            autoOpen: false,
            resizable: false,
            height:140,
            modal: true,
            hide: 'Slide',
            buttons: {
                "Delete": function() {
                    var del_id = {id : $("#del_id").val()};
                    $.ajax({
                        type: "POST",
                        url : "<?php echo site_url('daily/delete')?>",
                        data: del_id,
                        success: function(msg){
                            $('#show').html(msg);
                            $('#dialog-confirm' ).dialog( "close" );
                            //$( ".selector" ).dialog( "option", "hide", 'slide' );
                        }
                    });
 
                    },
                Cancel: function() {
                    $( this ).dialog( "close" );
                }
            }
        });
 
        $( "#form_input" ).dialog({
            autoOpen: false,
            height: 300,
            width: 350,
            modal: false,
            hide: 'Slide',
            buttons: {
                "Add": function() {
                    var form_data = {
                        id: $('#id').val(),
                        date: $('#date').val(),
                        name: $('#name').val(),
                        amount: $('#amount').val(),
                        ajax:1
                    };
 
                    $('#date').attr("disabled",true);
                    $('#name').attr("disabled",true);
                    $('#amount').attr("disabled",true);
 
                  $.ajax({
                    url : "<?php echo site_url('daily/submit')?>",
                    type : 'POST',
                    data : form_data,
                    success: function(msg){
                    $('#show').html(msg),
                    $('#date').val('<?php echo date('Y-m-d'); ?>'),
                    $('#id').val(''),
                    $('#name').val(''),
                    $('#amount').val(''),
                    $('#date').attr("disabled",false);
                    $('#name').attr("disabled",false);
                    $('#amount').attr("disabled",false);
                    $( '#form_input' ).dialog( "close" )
                    }
                  });
 
            },
                Cancel: function() {
                    $('#id').val(''),
                    $('#name').val('');
                    $('#amount').val('');
                    $( this ).dialog( "close" );
                }
            },
            close: function() {
                $('#id').val(''),
                $('#name').val('');
                $('#amount').val('');
            }
        });
 
    $( "#create-daily" )
            .button()
            .click(function() {
                $( "#form_input" ).dialog( "open" );
            });
    });
 
    $(".edit").live("click",function(){
        var id = $(this).attr("id");
        var date = $(this).attr("date");
        var name = $(this).attr("name");
        var amount = $(this).attr("amount");
 
        $('#id').val(id);
        $('#date').val(date);
        $('#name').val(name);
        $('#amount').val(amount);
 
        $( "#form_input" ).dialog( "open" );
 
        return false;
    });
 
    $(".delbutton").live("click",function(){
        var element = $(this);
        var del_id = element.attr("id");
        var info = 'id=' + del_id;
        $('#del_id').val(del_id);
        $( "#dialog-confirm" ).dialog( "open" );
 
        return false;
    });
    </script>
 
  </head>
 
  <body>
    <div id="show">
        <?php $this->load->view('daily/show'); ?>
    </div>
    <p>
        <button id="create-daily">Input New</button>
    </p>
 
<div id="form_input">
      <table>
        <?php echo form_open('daily/submit'); ?>
        <input type="hidden" value='' id="id" name="id">
        <tr >
            <td> <?php echo form_label('Date : '); ?></td>
            <td> <?php echo form_input('date',date('Y-m-d'),'id="date"'); ?></td>
        </tr>
        <tr>
            <td> <?php echo form_label('Name : ');?> </td>
            <td> <?php echo form_input('name','','id="name"'); ?></td>
        </tr>
        <tr>
            <td> <?php echo form_label('Amount : ');?> </td>
            <td> <?php echo form_input('amount','','id="amount"'); ?></td>
        </tr>
      </table>
    </div>
 
    <div id="dialog-confirm" title="Delete Item ?">
    <p>
        <span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span>
        <input type="hidden" value='' id="del_id" name="del_id">
        Are you sure?</p>
</div>
 
  </body>
</html>
Create Viewapplication\views\daily\show.php
<h1>Daily Notes</h1>
<table id="daily" class="ui-widget ui-widget-content" width="400px">
 <tr class="ui-widget-header ">
 <th>No</th>
 <th>Date</th>
 <th>Name</th>
 <th>Amount</th>
 <th>Edit</th>
 <th>Delete</th>
 </tr>
 <?
 $i=0;
 foreach ($query as $row){
 $i++;
 echo "<tr class=\"record\">";
 echo    "<td>$i</td>";
 echo    "<td>$row->date</td>";
 echo    "<td>$row->name</td>";
 echo    "<td>$row->amount</td>";
 echo    "<td><a href=\"#\" class=\"edit\" id=\"$row->id\" date=\"$row->date\" name=\"$row->name\" amount=\"$row->amount\">Edit</a></td>";
 echo    "<td><a class=\"delbutton\" id=\"$row->id\" href=\"#\" >Delete</a></td>";
 echo  "</tr>";
 }
 ?>
</table>

Download http://bit.ly/2GXWB1S

Sunday, August 4, 2013

CodeIgniter - jquery-ajax, jQueryUI - Autocomplete

CodeIgniter - jquery-ajax, jQueryUI - Autocomplete

Create Database table 

CREATE TABLE `country` (
  `id` smallint(5) UNSIGNED NOT NULL,
  `printable_name` varchar(255) NOT NULL,
  `CountryAbbrev` varchar(10) DEFAULT NULL,
  `CurrencyAbbr` varchar(4) DEFAULT NULL,
  `CurrencyRate` float DEFAULT NULL,
  `CurrencyCode` varchar(3) DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

ALTER TABLE `country`
  ADD PRIMARY KEY (`id`);

ALTER TABLE `country`
  MODIFY `id` smallint(5) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=289;

Create Controller
application\controllers\autocomplete.php

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

class Autocomplete extends CI_Controller { 
 
 public function __construct()  {
        parent:: __construct();
  $this->load->model("MAutocomplete");
  $this->load->helper("url");
  $this->load->helper('form');
    }
     
    public function index(){
        $this->load->view('autocomplete/show');
    }
     
    public function lookup(){
        // process posted form data
        $keyword = $this->input->post('term');
        $data['response'] = 'false'; //Set default response
        $query = $this->MAutocomplete->lookup($keyword); //Search DB
        if( ! empty($query) )
        {
            $data['response'] = 'true'; //Set response
            $data['message'] = array(); //Create array
            foreach( $query as $row )
            {
                $data['message'][] = array( 
                                        'id'=>$row->id,
                                        'value' => $row->printable_name,
                                        ''
                                     );  //Add a row to array
            }
        }
        if('IS_AJAX')
        {
            echo json_encode($data); //echo json string if ajax request
             
        }
        else
        {
            $this->load->view('autocomplete/index',$data); //Load html view of search results
        }
    }
}
Create Modal application\models\MAutocomplete.php
<?php
class MAutocomplete extends CI_Model{
    function lookup($keyword){
        $this->db->select('*')->from('country');
        $this->db->like('printable_name',$keyword,'after');
        $query = $this->db->get();    
         
        return $query->result();
    }
}
Create Viewapplication\views\autocomplete\show.php
<html lang="en-US">
    <head>
        <title>Codeigniter Autocomplete</title>
        <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.6/themes/base/jquery-ui.css" type="text/css" media="all" />
        <link rel="stylesheet" href="http://static.jquery.com/ui/css/demo-docs-theme/ui.theme.css" type="text/   css" media="all" />
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js" type="text/javascript"></script>
        <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.6/jquery-ui.min.js" type="text/javascript"></script>
        <meta charset="UTF-8">
         
        <style>
            /* Autocomplete
            ----------------------------------*/
            .ui-autocomplete { position: absolute; cursor: default; }   
            .ui-autocomplete-loading { background: white url('http://jquery-ui.googlecode.com/svn/tags/1.8.2/themes/flick/images/ui-anim_basic_16x16.gif') right center no-repeat; }*/
 
            /* workarounds */
            * html .ui-autocomplete { width:1px; } /* without this, the menu expands to 100% in IE6 */
 
            /* Menu
            ----------------------------------*/
            .ui-menu {
                list-style:none;
                padding: 2px;
                margin: 0;
                display:block;
            }
            .ui-menu .ui-menu {
                margin-top: -3px;
            }
            .ui-menu .ui-menu-item {
                margin:0;
                padding: 0;
                zoom: 1;
                float: left;
                clear: left;
                width: 100%;
                font-size:80%;
            }
            .ui-menu .ui-menu-item a {
                text-decoration:none;
                display:block;
                padding:.2em .4em;
                line-height:1.5;
                zoom:1;
            }
            .ui-menu .ui-menu-item a.ui-state-hover,
            .ui-menu .ui-menu-item a.ui-state-active {
                font-weight: normal;
                margin: -1px;
            }
        </style>
         
        <script type="text/javascript">
        $(this).ready( function() {
            $("#id").autocomplete({
                minLength: 1,
                source: 
                function(req, add){
                    $.ajax({
                        url: "<?php echo base_url(); ?>index.php/autocomplete/lookup",
                        dataType: 'json',
                        type: 'POST',
                        data: req,
                        success:    
                        function(data){
                            if(data.response =="true"){
                                add(data.message);
                            }
                        },
                    });
                },
            select: 
                function(event, ui) {
                    $("#result").append(
                        "<li>"+ ui.item.value + "</li>"
                    );                  
                },      
            });
        });
        </script>
         
    </head>
    <body>
        Country :
        <?php
            echo form_input('printable_name','','id="id"');
        ?>
        <ul>
            <div id="result"></div>
        </ul>
    </body>
</html>
View http://localhost/CODEIGNATER/autocomplete
/ Download http://bit.ly/2EaD1fA

CodeIgniter Upload Image and Resize

CodeIgniter Upload Image and Resize

Create Controller 
application\controllers\upload.php

Create folder name uploads root directory
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Upload extends CI_Controller {
 public function __construct() {
        parent:: __construct();
        $this->load->helper("url");
  $this->load->library('table');
  $this->load->helper('form');
    }
 
 public function index() {
  $this->load->view('upload_form');
  
 }
 public function upload_success() {
  $this->load->view('test/upload_success');
  
 }
 
 public function doUpload() {
  $config['upload_path'] = 'uploads/';
  $config['allowed_types'] = 'gif|jpg|jpeg|png';
  $config['max_size'] = '1000';
  $config['max_width'] = '1920';
  $config['max_height'] = '1280';      
  
  $this->load->library('upload', $config);
  
  if(!$this->upload->do_upload()) echo $this->upload->display_errors();
  else {
   $fInfo = $this->upload->data();
   $this->_createThumbnail($fInfo['file_name']);
   
   $data['uploadInfo'] = $fInfo;
   $data['thumbnail_name'] = $fInfo['raw_name'] . '_thumb' . $fInfo['file_ext'];
   $this->load->view('test/upload_success', $data); 
  }
 }
 
 public function _createThumbnail($fileName) {
  $config['image_library'] = 'gd2';
  $config['source_image'] = 'uploads/' . $fileName; 
  $config['create_thumb'] = TRUE;
  $config['maintain_ratio'] = TRUE;
  $config['width'] = 75;
  $config['height'] = 75;
  
  $this->load->library('image_lib', $config);
  if(!$this->image_lib->resize()) echo $this->image_lib->display_errors();
 }
}
Create View application\views\upload_form.php
<html>
  <head>
    <title>Upload an Image </title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  </head>
  <body>
    <div id="container">
     <h2>Upload an Image </h2>

  <?php echo form_open_multipart('upload/doUpload'); ?>
  <input type="file" name="userfile" />
  <p><input type="submit" value="Submit" name="submit" /></p>
  <?php echo form_close(); ?>
    </div>

  </body>
</html>
Create View application\views\test\upload_success.php

Upload an Image Success

View http://localhost/CODEIGNATER/upload/

Friday, August 2, 2013

CodeIgniter show record from database

CodeIgniter show record from database

Create Table
CREATE TABLE IF NOT EXISTS `daily` (
  `id` int(5) NOT NULL AUTO_INCREMENT,
  `date` date NOT NULL,
  `name` varchar(64) NOT NULL,
  `amount` double NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ;
Insert
INSERT INTO `daily` (`id`, `date`, `name`, `amount`) VALUES
(1, '2012-02-21', 'Kenshin', 5000),
(2, '2012-02-21', 'Naruto', 6000),
(3, '2012-02-21', 'Lufy', 7000),
(4, '2012-02-21', 'Zoro', 8000),
(5, '2012-02-21', 'Franky', 9000);

Controller
application\controllers\welcome.php
<?php 
class Welcome extends CI_Controller {

 function index(){ 
  $this->load->library('table');
  $this->load->database(); 
  $data['records']=$this->db->get('daily');
  $header = array('ID', 'Date', 'Name', 'Amount'); 
  $this->table->set_heading($header);
  $this->load->view('welcome/index',$data); 
 }
}
View
views\welcome\index.php
<div id="container">
 <h1>Welcome to CodeIgniter!</h1>
<div id="body">
 <?php echo $this->table->generate($records); ?>
 </div>
</div>

CodeIgniter Form Validation

CodeIgniter Form Validation 

Controller 
application\controllers\welcome.php

<?php
class Welcome extends CI_Controller {
 public function index()
 {
  //Form Validation
  $this->load->helper(array('form', 'url'));
  $this->load->library('form_validation');
  $this->form_validation->set_rules('username', 'Username', 'required');
  $this->form_validation->set_rules('password', 'Password', 'required');
  $this->form_validation->set_rules('passconf', 'Password Confirmation', 'required');
  $this->form_validation->set_rules('email', 'Email', 'required');
  //Validation Functions
  //$this->form_validation->set_rules('username', 'Username', 'required|min_length[5]|max_length[12]|is_unique[users.username]');
  //$this->form_validation->set_rules('password', 'Password', 'required|matches[passconf]');
  //$this->form_validation->set_rules('passconf', 'Password Confirmation', 'required');
  //$this->form_validation->set_rules('email', 'Email', 'required|valid_email|is_unique[users.email]');
  if ($this->form_validation->run() == FALSE)
  {
   $this->load->view('welcome_message');
  }
  else
  {
   $this->load->view('formsuccess');
  }
 }
}
application\views\welcome_message.php
<?php echo validation_errors(); ?>

<?php echo form_open('welcome'); ?>

<h5>Username</h5>
<input type="text" name="username" value="<?php echo set_value('username'); ?>" size="50" />

<h5>Password</h5>
<input type="text" name="password" value="<?php echo set_value('password'); ?>" size="50" />

<h5>Password Confirm</h5>
<input type="text" name="passconf" value="<?php echo set_value('passconf'); ?>" size="50" />

<h5>Email Address</h5>
<input type="text" name="email" value="<?php echo set_value('email'); ?>" size="50" />

<div><input type="submit" value="Submit" /></div>

</form>
Showing Errors Individually
<h5>Username</h5>
<?php echo form_error('username'); ?>
<input type="text" name="username" value="<?php echo set_value('username'); ?>" size="50" />

<h5>Password</h5>
<?php echo form_error('password'); ?>
<input type="text" name="password" value="<?php echo set_value('password'); ?>" size="50" />

<h5>Password Confirm</h5>
<?php echo form_error('passconf'); ?>
<input type="text" name="passconf" value="<?php echo set_value('passconf'); ?>" size="50" />

<h5>Email Address</h5>
<?php echo form_error('email'); ?>
<input type="text" name="email" value="<?php echo set_value('email'); ?>" size="50" />

Insert – Edit – Delete Codeigniter


Insert – Edit – Delete Codeigniter 

Create Database

CREATE TABLE IF NOT EXISTS `users` (
  `id` int(3) NOT NULL AUTO_INCREMENT,
  `username` varchar(15) NOT NULL,
  `password` text NOT NULL,
  `fullname` varchar(50) NOT NULL,
  PRIMARY KEY (`id`)
)

Setup Controller

application\controllers\user.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class User extends CI_Controller{ 
     /**
     * The __construct function is called so that I don't have to load the model each and every time.
     * And any change while refactoring or something else would mean change in only one place.
     */
    function __construct() {
        parent::__construct();
        $this->load->model('Model_user');
  $this->load->library('form_validation');
        $this->load->helper('form');
    }
 
    function index(){
        $data['query'] = $this->Model_user->getAll();
        $this->load->view('view_user/input',$data);
    }
 function submit(){
        if ($this->input->post('submit')){
                         
            if ($this->input->post('id')){
                $this->form_validation->set_rules('username', 'Username', 'required|min_length[5]|max_length[12]');
                $this->form_validation->set_rules('password', 'Password', 'matches[passconf]');
                $this->form_validation->set_rules('fullname', 'Fullname', 'required|min_length[5]|max_length[25]');
                 
                if ($this->form_validation->run() == FALSE){
                    $data['id'] = $this->input->post('id');
                    $data['username'] = set_value('username');
                    $data['fullname'] = set_value('fullname');
                    $this->load->view('view_user/edit',$data);
                }else{
                    $this->Model_user->update();
            redirect('view_user/index');
        }  
            }else{
                $this->form_validation->set_rules('username', 'Username', 'required|min_length[5]|max_length[12]');
                $this->form_validation->set_rules('password', 'Password', 'required|matches[passconf]');
                $this->form_validation->set_rules('passconf', 'Password Confirmation', 'required');
                $this->form_validation->set_rules('fullname', 'Fullname', 'required|min_length[5]|max_length[25]');
             
        if ($this->form_validation->run() == FALSE){
                        $data['query'] = $this->Model_user->getAll();
                        $this->load->view('view_user/input',$data);
                }else{
              $this->Model_user->save();
            redirect('user/index');
        }
      }
        }
    }
     
    function edit(){ 
    $id=$this->uri->segment(3);
    $data['result']=$this->Model_user->getUser($id);
     
    if (empty($id) or count($data['result'])==0 ){
        redirect('user/index');
    }else{   
        $result=$this->Model_user->getUser($id);
        $data['id'] = $result['id'];
        $data['username'] = $result['username'];
            $data['fullname'] = $result['fullname'];
        $this->load->view('view_user', $data);
    }   
  }
   
  function delete($id){
    $this->db->delete('user', array('id' => $id));
        redirect('user/index');
  }
}
Model application\models\Model_user.php
<?php
class Model_user extends CI_Model{
     
 function getAll(){
        $this->db->select('id,username,fullname');
                $this->db->from('users');
                $this->db->limit(10);
                $this->db->order_by('id','ASC');
                $query = $this->db->get();
 
                return $query->result();
    }
     
    function getUser($id){
    $this->db->where('id', $id);
    $query = $this->db->get('users');
     
    return $query->row_array();
    }
     
    function save(){
    $username = $this->input->post('username');
    $password = $this->input->post('password');
    $fullname = $this->input->post('fullname');
    $data = array(
      'username'=>$username,
      'password'=>md5($password),
      'fullname'=>$fullname
    );
    $this->db->insert('users',$data);
  }
   
  function update(){
    $id   = $this->input->post('id');
        $username = $this->input->post('username');
        $password = $this->input->post('password');
    $fullname = $this->input->post('fullname');
    if ($password==''){
        $data = array(
      'username'=>$username,
      'fullname'=>$fullname
    );
    }else{
        $data = array(
      'username'=>$username,
      'password'=>md5($password),
      'fullname'=>$fullname
    );
    }
     
    $this->db->where('id',$id);
    $this->db->update('users',$data);   
  }
}
View application\views\view_user\input.php
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Data User</title>
  </head>
  <body>
    <div id="form_input" title="Input / Edit Data">
      <table>
        <?php echo validation_errors(); ?>
        <?php echo form_open('user/submit'); ?>
        <tr >
            <td> <?php echo form_label('User Name : '); ?></td>
            <td> <?php echo form_input('username',set_value('username'),'id="username"'); ?></td>
        </tr>
        <tr>
            <td> <?php echo form_label('Password : ');?> </td>
            <td> <?php echo form_password('password','','id="password"'); ?></td>
        </tr>
         <tr>
            <td> <?php echo form_label('Repeat Password : ');?> </td>
            <td> <?php echo form_password('passconf','','id="passconf"'); ?></td>
        </tr>
        <tr>
            <td> <?php echo form_label('Full Name : ');?> </td>
            <td> <?php echo form_input('fullname', set_value('fullname'),'id="fullname"'); ?></td>
        </tr>
        <tr>
                <td><?php echo form_submit('submit','Save')?>
        </tr>
      </table>
      </div>
      <div id="show">
        <?php $this->load->view('view_user/show'); ?>
    </div>
    </div>
  </body>
</html>
application\views\view_user\show.php
<?php
    if (isset($query) && count($query) > 0){
    ?>
    <h1>Data User</h1>
    <table width="400" border="1">
    <tr >
     <th>No</th>
     <th>Username</th>
     <th>Fullname</th>
     <th>Edit</th>
     <th>Delete</th>
 </tr>
 <?php
 $i=0;
 foreach ($query as $row){
 $i++;
 echo "<tr class=\"record\">";
 echo    "<td>$i</td>";
 echo    "<td>$row->username</td>";
 echo    "<td>$row->fullname</td>";
 echo    "<td><a href=".base_url()."index.php/user/edit/$row->id>Edit</a></td>";
 echo    "<td><a href=".base_url()."index.php/user/delete/$row->id>Delete</a></td>";
 echo  "</tr>";
 }
 ?>
</table>
<?php
    }
?>

Simple Login with CodeIgniter in PHP

Simple Login with CodeIgniter in PHP 

 Create the database

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

insert into users (username, password) values ('admin', MD5('password'));
 
Configure CodeIgniter 

application/config/database.php 
 
Default Controller
application/config/routes.php 
call landing controller login
$route['default_controller'] = "login";
 
Default Libraries 
application/config/autoload.php
handle user sessions, and also the URL helper for internal link generation
$autoload['libraries'] = array('database','session');
$autoload['helper'] = array('url'); 

Encryption Key
application/config/config.php
$config['encryption_key'] = 'REALLY_LONG_NUMBER';
 
The Code
 
User Model (application/models/user.php) 

<?php
Class User extends CI_Model
{
 function login($username, $password)
 {
   $this -> db -> select('id, username, password');
   $this -> db -> from('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;
   }
 }
}
?>
Login Controller (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');
 }

}

?>
Login View (application/views/login_view.php)
   <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>
VerifyLogin Controller (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(
         'id' => $row->id,
         '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;
   }
 }
}
?>
Home Controller (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');
 }

}

?>
Home Page View (application/views/home_view.php)
<html>
 <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>

Saturday, June 15, 2013

jQuery and ajax with Codeigniter

jQuery and ajax with Codeigniter

application\controllers\products.php
<?php
class Products extends CI_Controller{
 
 function __construct(){
  parent::__construct();
 }
 
 function index() {
        $this->load->view('products');
    }
 public function get_all_users(){

  $query = $this->db->get('products');
  if($query->num_rows > 0){
   $header = false;
   $output_string = '';
   $output_string .=  "<table border='1'>";
   foreach ($query->result() as $row){
    $name = $row->name;
    $output_string .= '<tr>';
    $output_string .= "<th>$name</th>"; 
    $output_string .= '</tr>';    
   }     
   $output_string .= '</table>';
  }
  else{
   $output_string = 'There are no results';
  }
   
  echo json_encode($output_string);
 }
 }
?>
application\views\products.php
<script language='JavaScript' type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js'></script>
<button type='button' name='getdata' id='getdata'>Get Data.</button>
<div id='result_table'></div>
<script type='text/javascript' language='javascript'>
$('#getdata').click(function(){
    $.ajax({
            url: '<?php echo base_url().'products/get_all_users';?>',
            type:'POST',
            dataType: 'json',
            success: function(output_string){
                    $('#result_table').append(output_string);
                } // End of success function of ajax form
            }); // End of ajax call 
 
});
</script>

Sunday, June 9, 2013

Removing index.php from URL in Codeigniter

Removing index.php from URL in Codeigniter

Go to your root folder: create .htaccess

# Customized error messages.
ErrorDocument 404 /index.php
 
# Set the default handler.
DirectoryIndex index.php
 
# Various rewrite rules.
<IfModule mod_rewrite.c>
  RewriteEngine on
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule ^(.*)$ index.php?/$1 [L,QSA]
</IfModule>

Saturday, June 8, 2013

Login Page With CodeIgniter Framework in PHP

Login Page With CodeIgniter Framework in PHP

1. Database table

CREATE TABLE IF NOT EXISTS `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(255) NOT NULL,
  `password` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;


INSERT INTO `users` (`id`, `username`, `password`) VALUES
(1, 'admin', 'admin');


2. Set application\config\routes.php
$route['default_controller'] = "login";
$route['404_override'] = '';

3. set autoload application\config\autoload.php
$autoload['libraries'] = array('database', 'session');

4. set the encryption_key
application\config\config.php
$config['encryption_key'] = 'REALLY_LONG_NUMBER';

Create Model application\models\user.php


<?php
Class User extends CI_Model
{
 function login($username, $password)
 {
   $this -> db -> select('username, password');
   $this -> db -> from('users');
   $this -> db -> where('username = ' . "'" . $username . "'");
   $this -> db -> where('password = ' . "'" . $password . "'");
   $this -> db -> limit(1);
  
   $query = $this -> db -> get();

   if($query -> num_rows() == 1)
   {
     return $query->result();
   }
   else
   {
     return false;
   }
 }
}
?>
Create a controller 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', 'url'));
   $this->load->view('login_view');
 }
 
}
 
?>
Create the home controller 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');
 }
 
}
 
?>
Create the view controllers\login_view.php
<html xmlns="http://www.w3.org/1999/xhtml">
 <head>
   <title>Simple Login with CodeIgniter</title>
 </head>
 <body bgcolor="pink">
   <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>
VerifyLogin Controller (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(
          //'id' => $row->id,
          '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;
    }
  }
 }
 ?>
Create the home view
<html xmlns="http://www.w3.org/1999/xhtml">
 <head>
   <title>Simple Login with CodeIgniter - Private Area</title>
 </head>
 <body bgcolor="pink">
   <h1>Home</h1>
   <h2>Welcome <?php echo $username; ?>!</h2>
   <a href="home/logout">Logout</a>
  </body>
 </html>

Related Post