article

Saturday, August 31, 2013

Pagenation using PHP Class

Pagenation using PHP Class

Crate Database table
CREATE TABLE `countries` (
  `ID` smallint(5) unsigned NOT NULL auto_increment,
  `Country` varchar(255) NOT NULL,
  `CountryAbbrev` varchar(10) default NULL,
  `CurrencyAbbr` varchar(4) default NULL,
  `CurrencyRate` float default NULL,
  `CurrencyCode` varchar(3) default NULL,
  PRIMARY KEY  (`ID`)
) ENGINE=MyISAM AUTO_INCREMENT=289 DEFAULT CHARSET=latin1;

Download table countries
index.php
<?php
    require_once('Pagination.class.php');
    $row_per_page = 20;
    $pagination = new CompletePagination($row_per_page);
    
    $link = mysql_connect('localhost', 'root', '');
    mysql_selectdb('test');
    
    $where = "";
    
    if(isset($_POST['txt_name']))
        $where = " WHERE Country LIKE '%{$_POST['txt_name']}%'";
    else if(isset($_GET['txt_name']) && isset($_GET['page_no']))
        $where = " WHERE Country LIKE '%{$_GET['txt_name']}%'";

    $query_count = "SELECT COUNT(Country) AS tot_rec FROM countries ".$where;
    $result_count = mysql_query($query_count);
    $record_count = mysql_fetch_array($result_count);
    $total_rec = $record_count['tot_rec'];
    
    $pagination->total_rows = $total_rec;    
    $pagination->show_dropdown = true;
    $pagination->show_total_records = true;
    $pagination->show_page_no = true;
    $pagination->show_ellipsis = 20;   //Show Ellipsis if total Pages are greater than or eqaul to 100
    $pagination_html = $pagination->showCompletePagination();

    $pagination->show_ellipsis = 10;
    $pagination->show_dropdown = false;
    $pagination->show_total_records = false;
    $pagination->show_page_no = false;
    $pagination_html2 = $pagination->showCompletePagination();
    
    $query = "SELECT Country, CountryAbbrev, CurrencyAbbr FROM countries ".$where." LIMIT ".$pagination->getLimit() . ", " . $row_per_page;
    $result = mysql_query($query);
?>
<!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>Pagination</title>
        <link rel="stylesheet" type="text/css" href="completepagination.css" />
    </head>
    <body>
        <div align="center">
        <?php echo $pagination_html; ?>
        <form method="post" action="">
            Country Name: <input type="text" name="txt_name" value="<?php echo @$_REQUEST['txt_name'];?>" />
            <input type="submit" value="Submit" />            
        </form>
        <table border="1" cellpadding="2" cellspacing="2">
            <thead>
            <tr>
                <th>Country</th>
                <th>Country Abb</th>
                <th>Currency Abb</th>
            </tr>
            </thead>
            <tbody>
                <?php
                    while($record = mysql_fetch_array($result)){
                ?>
                <tr>
                    <td><?php echo $record['Country'];?></td>
                    <td><?php echo $record['CountryAbbrev'];?></td>
                    <td><?php echo $record['CurrencyAbbr'];?></td>
                </tr>
                <?php } ?>
            </tbody>
        </table>
        <?php echo $pagination_html2;?>
        </div>
    </body>
</html>
Pagination.class.php
<?php
class CompletePagination 
{
    private $rows_per_page;
    private $url;
    private $page_no;
    
    public $total_rows;
    public $show_dropdown;
    public $show_total_records;
    public $show_page_no;
    public $show_ellipsis = 9;     //Show ... if total pages are more than 10

    /**
     *
     * @param int $rperpage - show the record per page
     * @param int $totrows - total records
     */
    public function __construct($rperpage, $totrows = "") 
    {
        $this->rows_per_page = $rperpage;
        $this->total_rows = $totrows;
        $this->setPageNumber();
        $this->generateCompleteURL();
    }

    /**
     * function sets the pageNumber
     */
    private function setPageNumber() 
    {
        if($_POST)
            $this->page_no = 1;
        else
        {
            if (!isset($_REQUEST['page_no']) && @$_REQUEST['page_no'] == "")
                $this->page_no = 1;
            else
                $this->page_no = $_REQUEST['page_no'];
        }
    }

    /**
     * function gets the limit of pagination
     * @return int 
     */
    public function getLimit() 
    {
        return ($this->page_no - 1) * $this->rows_per_page;
    }

    /**
     * This function generates the complete URL along with the query string
     */
    private function generateCompleteURL() 
    {
        $page_query = (count($_REQUEST) == 0 ? "page_no=" : "&page_no=");

        if (isset($_REQUEST['page_no']))
            unset($_REQUEST['page_no']);

        $this->url = $_SERVER['PHP_SELF'] . "?" . http_build_query($_REQUEST) . $page_query;
    }

    /**
     * function returns the last page, that is generates as the result of Pagination
     * @return int 
     */
    private function getLastPage() 
    {
        return ceil($this->total_rows / $this->rows_per_page);
    }

    /**
     * function generates the DropDown for Pagination
     * @return string 
     */
    private function generateDropdown() 
    {
        if ($this->total_rows == 0)
            return "";

        $str = "";
        $str .= '<select name="drp_page_no" id="drp_page_no" onchange="document.location.href = this.value;">';
        for ($cnt = 1; $cnt <= $this->getLastPage(); $cnt++) 
        {
            if (isset($this->page_no) && $this->page_no == $cnt)
                $str .= '<option value="' . $this->url . $cnt . '" selected="selected">' . $cnt . '</option>';
            else
                $str .= '<option value="' . $this->url . $cnt . '">' . $cnt . '</option>';
        }
        $str .= '</select>';
        return $str;
    }

    /**
     * function generates the complete pagination
     * @return string 
     */
    public function showCompletePagination() 
    {
        $pagination = "";
        $lpm1 = $this->getLastPage() - 1;
        $page = $this->page_no;
        $prev = $this->page_no - 1;
        $next = $this->page_no + 1;

        $pagination .= "<div class=\"pagination\"";

        if (@$margin || @$padding) 
        {
            $pagination .= " style=\"";
            if ($margin)
                $pagination .= "margin: $margin;";
            if ($padding)
                $pagination .= "padding: $padding;";
            $pagination .= "\"";
        }
        if ($this->show_total_records)
            $pagination .= "><span class='tableStandardBold' style='margin-right:50px;'> Total Number of record(s) found: " . $this->total_rows . " </span>";
        else
            $pagination .= ">";


        if ($this->getLastPage() > 1) 
        {            
            if ($page > 1)
            {
                $pagination .= "<a href={$this->url}1>« first</a>";
                $pagination .= "<a href=$this->url$prev>‹ prev</a>";
            }
            else
            {
                $pagination .= "<span class=\"disabled\">« first</span>";
                $pagination .= "<span class=\"disabled\">‹ prev</span>";
            }


            if ($this->getLastPage() < $this->show_ellipsis) 
            {
                for ($counter = 1; $counter <= $this->getLastPage(); $counter++) 
                {
                    if ($counter == $page)
                        $pagination .= "<span class=\"current\">" . $counter . "</span>";
                    else
                        $pagination .= "<a href=$this->url$counter>" . $counter . "</a>";
                }
            }
            elseif ($this->getLastPage() >= $this->show_ellipsis)
            {
                if ($page < 4) 
                {
                    for ($counter = 1; $counter < 6; $counter++) 
                    {
                        if ($counter == $page)
                            $pagination .= "<span class=\"current\">" . $counter . "</span>";
                        else
                            $pagination .= "<a href=\"$this->url$counter\">" . $counter . "</a>";
                    }
                    $pagination .= "...";
                    $pagination .= "<a href=$this->url$lpm1>" . $lpm1 . "</a>";
                    $pagination .= "<a href={$this->url}{$this->getLastPage()}>" . $this->getLastPage() . "</a>";
                }
                elseif ($this->getLastPage() - 3 > $page && $page > 1) 
                {
                    $pagination .= "<a href={$this->url}1>1</a>";
                    $pagination .= "<a href={$this->url}2>2</a>";
                    $pagination .= "...";
                    for ($counter = $page - 1; $counter <= $page + 1; $counter++) {
                        if ($counter == $page)
                            $pagination .= "<span class=\"current\">" . $counter . "</span>";
                        else
                            $pagination .= "<a href=$this->url$counter>" . $counter . "</a>";
                    }
                    $pagination .= "...";
                    $pagination .= "<a href=$this->url$lpm1>$lpm1</a>";
                    $pagination .= "<a href={$this->url}{$this->getLastPage()}>" . $this->getLastPage() . "</a>";
                }
                else 
                {
                    $pagination .= "<a href={$this->url}1>1</a>";
                    $pagination .= "<a href={$this->url}2>2</a>";
                    $pagination .= "...";
                    for ($counter = $this->getLastPage() - 4; $counter <= $this->getLastPage(); $counter++) 
                    {
                        if ($counter == $page)
                            $pagination .= "<span class=\"current\">" . $counter . "</span>";
                        else
                            $pagination .= "<a href=$this->url$counter>" . $counter . "</a>";
                    }
                }
            }

            if ($page < $counter - 1)
            {
                $pagination .= "<a href=$this->url$next>next ›</a>";
                $pagination .= "<a href={$this->url}{$this->getLastPage()}>last »</a>";
            }
            else
            {
                $pagination .= "<span class=\"disabled\">next ›</span>";
                $pagination .= "<span class=\"disabled\">last »</span>";
            }

            if ($this->show_dropdown)
                $pagination .= "<span class='tableStandardBold' style='margin-left:20px;'>Go to page:  " . $this->generateDropdown() . "</span>\n";

            if ($this->show_page_no)
            {
                $page = 1;
                if (isset($this->page_no) && $this->page_no != "")
                    $page = $this->page_no;
                $pagination .= "<span class='tableStandardBold' style='margin-left:20px;'> Page " . $page . " of " . $this->getLastPage() . "</span>\n";
            }

            $pagination .= "</div>\n";
        }
        return $pagination;
    }

}

?>

Sunday, August 25, 2013

Creating simple class php interest Calculator

Creating simple class php interest Calculator 

<?php
//Creating class interestCalculator
class interestCalculator
{
public $rate;
public $duration;
public $capital;
public function calculateInterest()
{
return ($this->rate*$this->duration*$this->capital)/100;
}
}
//Creating  various object of class interestCalculator to calculate interest on various amount
$cls1 = new interestCalculator();
$cls2 = new $cls1;
$cls1->rate =2;
$cls1->duration =3;
$cls1->capital = 300;

$cls2->capital = 400;

$interest1 = $cls1->calculateInterest();
$interest2  = $cls2->calculateInterest();
echo "$interest1 -- $interest2";

Saturday, August 24, 2013

Create Registration Modal box using bootstrap

Create Registration Modal box using bootstrap

Bootstrap Sleek, intuitive, and powerful front-end framework for faster and easier web development

url bootstrapjs
http://getbootstrap.com/2.3.2/javascript.html#modals

Download 

<html>
  <head>
    <title>Bootstrap registration</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="css/bootstrap.min.css" rel="stylesheet" media="screen">
 <style>
    body {
      padding-top: 60px;
      padding-bottom: 40px;
    }
 .modal {
    width: auto;
    left: 57%;
}
label.checkbox {
    float: none;
    margin-top: -6px;
    margin-bottom: 15px;
    margin-left: 1px;
    width: 280px;
}
  </style>
  </head>
  <body>
 <a href="#myModal" role="button" class="btn" data-toggle="modal">Launch demo modal</a>
 <!-- Modal -->
 <div id="myModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
   <div class="modal-header">
      <button type="button" class="close" data-dismiss="modal">x</button>
      <h3>New User Details</h3>
    </div>
    <div class="modal-body">
        <p><input type="text" class="span4" name="first_name" id="first_name" placeholder="First Name"></p>
        <p><input type="text" class="span4" name="last_name" id="last_name" placeholder="Last Name"></p>
        <p><input type="text" class="span4" name="email" id="email" placeholder="Email"></p>
        <p>
          <select class="span4" name="teamId" id="teamId">
            <option value="">Team Number...</option>
            <option value="1">1</option>
            <option value="2">2</option>
          </select>
        </p>
        <p>
          <label class="checkbox span4">
            <input type="checkbox" id="isAdmin" name="isAdmin"> Is an admin?
          </label>
        </p>
        <p><input type="password" class="span4" name="password" id="password" placeholder="Password"></p>
        <p><input type="password" class="span4" name="password2" id="password2" placeholder="Confirm Password"></p>
    </div>
    <div class="modal-footer">
      <a href="#" class="btn btn-warning" data-dismiss="modal">Cancel</a>
      <a href="#" id="btnModalSubmit" class="btn btn-primary">Create</a>
    </div>
 </div>
    <script src="http://code.jquery.com/jquery.js"></script>
    <script src="js/bootstrap.min.js"></script>
  </body>
</html>

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;
    });

});

CSS Drop Down Menu

CSS Drop Down Menu

Save image 
 
<style type="text/css">
#cssmenu ul,
#cssmenu li,
#cssmenu span,
#cssmenu a {
  margin: 0;
  padding: 0;
  position: relative;
}
#cssmenu:after,
#cssmenu ul:after {
  content: '';
  display: block;
  clear: both;
}
#cssmenu a {
  color: #ffffff;
  display: inline-block;
  font-family: 'Lucida Grande', 'Lucida Sans Unicode', Helvetica, Arial, Verdana, sans-serif;
  font-size: 12px;
  min-width: 35px;
  text-align: center;
  text-decoration: none;
  text-shadow: 0 -1px 0 #333333;
}
#cssmenu ul {
  list-style: none;
}
#cssmenu > ul > li {
  float: left;
}
#cssmenu > ul > li.active a {
  background: #646464 url(menu_assets/images/grad_dark.png) repeat-x left bottom;
  background: -moz-linear-gradient(top, #646464 0%, #4a4a4a 100%);
  background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #646464), color-stop(100%, #4a4a4a));
  background: -webkit-linear-gradient(top, #646464 0%, #4a4a4a 100%);
  background: -o-linear-gradient(top, #646464 0%, #4a4a4a 100%);
  background: -ms-linear-gradient(top, #646464 0%, #4a4a4a 100%);
  background: linear-gradient(to bottom, #646464 0%, #4a4a4a 100%);
  filter: progid:dximagetransform.microsoft.gradient(startColorstr='#646464', endColorstr='#4a4a4a', GradientType=0);
  box-shadow: inset 0 0 10px #222222, inset 0 10px 10px #222222;
  -moz-box-shadow: inset 0 0 10px #222222, inset 0 10px 10px #222222;
  -webkit-box-shadow: inset 0 0 10px #222222, inset 0 10px 10px #222222;
  filter: none;
}
#cssmenu > ul > li.active a:hover {
  background: -moz-linear-gradient(top, #646464 0%, #4a4a4a 100%);
  background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #646464), color-stop(100%, #4a4a4a));
  background: -webkit-linear-gradient(top, #646464 0%, #4a4a4a 100%);
  background: -o-linear-gradient(top, #646464 0%, #4a4a4a 100%);
  background: -ms-linear-gradient(top, #646464 0%, #4a4a4a 100%);
  background: linear-gradient(to bottom, #646464 0%, #4a4a4a 100%);
  filter: progid:dximagetransform.microsoft.gradient(startColorstr='#646464', endColorstr='#4a4a4a', GradientType=0);
  filter: none;
}
#cssmenu > ul > li a {
  box-shadow: inset 0 0 0 1px #8a8a8a;
  -moz-box-shadow: inset 0 0 0 1px #8a8a8a;
  -webkit-box-shadow: inset 0 0 0 1px #8a8a8a;
  background: #4a4a4a url(images/grad_dark.png) repeat-x left top;
  background: -moz-linear-gradient(top, #8a8a8a 0%, #707070 50%, #626262 51%, #787878 100%);
  background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #8a8a8a), color-stop(50%, #707070), color-stop(51%, #626262), color-stop(100%, #787878));
  background: -webkit-linear-gradient(top, #8a8a8a 0%, #707070 50%, #626262 51%, #787878 100%);
  background: -o-linear-gradient(top, #8a8a8a 0%, #707070 50%, #626262 51%, #787878 100%);
  background: -ms-linear-gradient(top, #8a8a8a 0%, #707070 50%, #626262 51%, #787878 100%);
  background: linear-gradient(to bottom, #8a8a8a 0%, #707070 50%, #626262 51%, #787878 100%);
  filter: progid:dximagetransform.microsoft.gradient(startColorstr='#8a8a8a', endColorstr='#787878', GradientType=0);
  border-bottom: 1px solid #5d5d5d;
  border-top: 1px solid #5d5d5d;
  border-right: 1px solid #5d5d5d;
  line-height: 34px;
  padding: 0 35px;
  filter: none;
}
#cssmenu > ul > li a:hover {
  background: #8a8a8a url(images/grad_dark.png) repeat-x left bottom;
  background: -moz-linear-gradient(top, #646464 0%, #4a4a4a 50%, #3b3b3b 51%, #525252 100%);
  background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #646464), color-stop(50%, #4a4a4a), color-stop(51%, #3b3b3b), color-stop(100%, #525252));
  background: -webkit-linear-gradient(top, #646464 0%, #4a4a4a 50%, #3b3b3b 51%, #525252 100%);
  background: -o-linear-gradient(top, #646464 0%, #4a4a4a 50%, #3b3b3b 51%, #525252 100%);
  background: -ms-linear-gradient(top, #646464 0%, #4a4a4a 50%, #3b3b3b 51%, #525252 100%);
  background: linear-gradient(to bottom, #646464 0%, #4a4a4a 50%, #3b3b3b 51%, #525252 100%);
  filter: progid:dximagetransform.microsoft.gradient(startColorstr='#8a8a8a', endColorstr='#787878', GradientType=0);
  filter: none;
}
#cssmenu > ul > li:first-child a {
  border-radius: 5px 0 0 5px;
  -moz-border-radius: 5px 0 0 5px;
  -webkit-border-radius: 5px 0 0 5px;
  border-left: 1px solid #5d5d5d;
}
#cssmenu > ul > li:last-child a {
  border-radius: 0 5px 5px 0;
  -moz-border-radius: 0 5px 5px 0;
  -webkit-border-radius: 0 5px 5px 0;
}
#cssmenu .has-sub:hover ul {
  display: block;
}
#cssmenu .has-sub ul {
  display: none;
  position: absolute;
  top: 36px;
  left: -1px;
  min-width: 100%;
  text-align: center;
  /* IE7 */

  *width: 100%;
}
#cssmenu .has-sub ul li {
  text-align: center;
}
#cssmenu .has-sub ul li a {
  border-top: 0 none;
  border-left: 1px solid #5d5d5d;
  display: block;
  line-height: 120%;
  padding: 9px 5px;
  text-align: center;
}
</style>
<div id='cssmenu'>
<ul>
   <li class='active '><a href='index.html'><span>Home</span></a></li>
   <li class='has-sub '><a href='#'><span>Products</span></a>
      <ul>
         <li><a href='#'><span>Product 1</span></a></li>
         <li><a href='#'><span>Product 2</span></a></li>
      </ul>
   </li>
   <li><a href='#'><span>About</span></a></li>
   <li><a href='#'><span>Contact</span></a></li>
</ul>
</div>

Tuesday, August 20, 2013

Create CSS3 Button

Create CSS3 Button
<html>
<head>
<style>
body {background-color:#1B1B1D;}
input[type=submit]{
 
 /* Submit button */
 
 opacity:0.9;
 position:absolute;
 top:262px;
 left:25px;
 width: 239px;
 height:36px;
 cursor:pointer;
 border-radius:6px;
 box-shadow:0 1px 1px #888;
 border:none;
 color:#fff;
 font:14px/36px 'Segoe UI Light','Segoe UI',Arial,sans-serif;
 
 /* CSS3 Gradients */
 
 background-image: linear-gradient(bottom, rgb(80,102,127) 50%, rgb(87,109,136) 50%, rgb(106,129,155) 100%);
 background-image: -o-linear-gradient(bottom, rgb(80,102,127) 50%, rgb(87,109,136) 50%, rgb(106,129,155) 100%);
 background-image: -moz-linear-gradient(bottom, rgb(80,102,127) 50%, rgb(87,109,136) 50%, rgb(106,129,155) 100%);
 background-image: -webkit-linear-gradient(bottom, rgb(80,102,127) 50%, rgb(87,109,136) 50%, rgb(106,129,155) 100%);
 background-image: -ms-linear-gradient(bottom, rgb(80,102,127) 50%, rgb(87,109,136) 50%, rgb(106,129,155) 100%);
 
 background-image: -webkit-gradient(
  linear,
  left bottom,
  left top,
  color-stop(0.5, rgb(80,102,127)),
  color-stop(0.5, rgb(87,109,136)),
  color-stop(1, rgb(106,129,155))
 );
}

input[type=submit]:hover{
 opacity:1;
}
</style>
</head>
<body>
<input type="submit" name="submit" value="Recover" />
</body>
</html>

Simple Dropdown Menu like apple

Simple Dropdown Menu like apple
<style type="text/css">
#cssmenu ul {margin: 0; padding: 7px 6px 0; background: #7d7d7d url(menu_assets/images/overlay.png) repeat-x 0 -110px; line-height: 100%; border-radius: 1em; font: normal .8em/1.5em Arial, Helvetica, sans-serif; -webkit-border-radius: 5px; -moz-border-radius: 5px; border-radius: 5px; -webkit-box-shadow: 0 1px 3px rgba(0,0,0, .4); -moz-box-shadow: 0 1px 3px rgba(0,0,0, .4);}
#cssmenu li {margin: 0 5px; padding: 0 0 8px; float: left; position: relative; list-style: none; }
#cssmenu a,
#cssmenu a:link {font-weight: bold; color: #e7e5e5; text-decoration: none; display: block; padding:  8px 20px; margin: 0; border-radius: 5px; -webkit-border-radius: 5px; -moz-border-radius: 5px;  text-shadow: 0 1px 1px rgba(0,0,0, .3); }
#cssmenu a:hover {background: #000; color: #fff;}
#cssmenu .active a, 
#cssmenu li:hover > a {background: #666 url(menu_assets/images/overlay.png) repeat-x 0 -40px; color: #444; border-top: solid 1px #f8f8f8; -webkit-box-shadow: 0 1px 1px rgba(0,0,0, .2); -moz-box-shadow: 0 1px 1px rgba(0,0,0, .2); box-shadow: 0 1px 1px rgba(0,0,0, .2); text-shadow: 0 1px 0 rgba(255,255,255, 1); }
#cssmenu ul ul li:hover a,
#cssmenu li:hover li a {background: none; border: none; color: #666; -webkit-box-shadow: none; -moz-box-shadow: none;}
#cssmenu ul ul a:hover {background: #8f8f8f url(menu_assets/images/overlay.png) repeat-x 0 -100px !important; color: #fff !important; -webkit-border-radius: 5px; -moz-border-radius: 5px; border-radius: 5px; text-shadow: 0 1px 1px rgba(0,0,0, .1);}
#cssmenu li:hover > ul {display: block;}
#cssmenu ul ul {display: none; margin: 0; padding: 0; width: 185px; position: absolute; top: 40px; left: 0; background: #ddd url(menu_assets/images/overlay.png) repeat-x 0 0; border: solid 1px #b4b4b4; -webkit-border-radius: 5px; -moz-border-radius: 5px; border-radius: 5px; -webkit-box-shadow: 0 1px 3px rgba(0,0,0, .3); -moz-box-shadow: 0 1px 3px rgba(0,0,0, .3); box-shadow: 0 1px 3px rgba(0,0,0, .3);}
#cssmenu ul ul li {float: none; margin: 0; padding: 3px; }
#cssmenu ul ul a {font-weight: normal; text-shadow: 0 1px 0 #fff; }
#cssmenu ul:after {content: '.'; display: block; clear: both; visibility: hidden; line-height: 0; height: 0;}
* html #cssmenu  ul {height: 1%;}</style>
<div id='cssmenu'>
<ul>
   <li class='active '><a href='index.html'><span>Home</span></a></li>
   <li class='has-sub '><a href='#'><span>Products</span></a>
      <ul>
         <li><a href='#'><span>Product 1</span></a></li>
         <li><a href='#'><span>Product 2</span></a></li>
      </ul>
   </li>
   <li><a href='#'><span>About</span></a></li>
   <li><a href='#'><span>Contact</span></a></li>
</ul>
</div>

Create Modal Box Using Jquery

Create Modal Box Using Jquery
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Modal Box</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
 //Buttons that trigger the popup 
 $(".signup_popup_button").click(function(e) {
  $(this).doPopup();
  //this is needed so it wont fire the closePopup function when we click the body
  e.stopPropagation();
 });

 $.fn.doPopup = function(options) {
  var defaults = {
   slide: 0,
  };
  //popup window div
  var popup_window = $("#popup_window");
  //loader
  var loader = $(".loader");
  //state of popup
  //if its 0 its hidden , 1 its shown
  var state = 0;
  //self explanotary, centers the popup window
  function centerPopup(){
   var windowWidth = document.documentElement.clientWidth;
   var windowHeight = document.documentElement.clientHeight;
   var popupWidth = popup_window.width();
   //centering
   popup_window.css({
    "position": 'absolute',
    "top": '21%',
    "left": windowWidth/2-popupWidth/2
   });
   $("#bg_color").css({  
    "height": windowHeight  
   });
  }
  //remove the background color when popup is active
  function backgroundFade(){
   $("#bg_color").css({  
    "opacity": "0.7"  
   });
   $("#bg_color").fadeIn("fast");
  }
  //closes the popup
  function closePopup(){
   //remove background fade
   $("#bg_color").fadeOut("fast")
   //close popup
   popup_window.fadeOut("fast");
  }
  //show the page content
  function showContent(){
   //show div containing the forms
   $(".popup_content_data").show();
   
  }
  
  //this is needed so the popup remains shown
  popup_window.click(function(e){
   e.stopPropagation();
  });
  //when we click the X button on the top right corner of the popup
  //we close the window
  $(".popup_window_close").click(function(){
   state=0;
   closePopup();
  });
  //when we click on the body we close the popup window
  $("body").click(function(){
   if (state == 1){
    closePopup();
    state = 0;
   }
  });
  //Shows the Popup
  function showPopup(type){
   if (state == 0){
    //fade background on click
    backgroundFade()
    if (type == ""){
     $(".popup_content_data").hide();
     //show the loading text and image
     loader.show();
    }
    //dynamically show the popup window
    centerPopup();
    //show the popup window
    popup_window.show();
    //animate the popup window and hide the loader
    setTimeout(function(){
     loader.hide();
     showContent();
    }, 200);
    state = 1;
   }
  }

  showPopup("fade");
 };
})(jQuery);
</script>
<style>
body{
 font-size:13px;
 font-family:Tahoma;
    border: 0 none;
    margin: 0;
    outline: 0 none;
    padding: 0;
    vertical-align: baseline;
}
h1,h2,h3{
 margin:0;
 padding:0;
}



#signup_submit{
 min-width:100px;
 max-width:135px;
 display:inline-block;
 height:18px;
 border:1px solid #B5B5B5;
 padding:5px;
 background: -moz-linear-gradient(center top , #FFFFFF, #E3E3E3) repeat scroll 0 0 #F6F6F6;
 -ms-filter: "progid:DXImageTransform.Microsoft.gradient(GradientType=0, startColorstr=#FFFFFF, endColorstr=#E3E3E3)";
 background-image: -o-linear-gradient(#FFFFFF,#E3E3E3);
 color:#3D3D3D;
 cursor:pointer;
 background-color:#E8E8E8;
 border-radius:3px;
}
.message_error{
 border:solid 1px #a1a1a1; 
 background-color: #FFC922;
 border-radius:5px;
 color: #3B3B3B;
 width:96%;
 padding:5px;
 display:none;
 float:left;
 margin-top:10px;
}
.signup_popup_button{
 float:left;
 width:78px;
 margin-left:-1px;
 text-align:center;
}
.recoverpass_popup_button{
 float:left;
 width:110px;
 margin-left:-1px;
 border-radius:0;
 text-align:right;
}
.activate_account_popup_button{
 float:left;
 border-radius:0 3px 3px 0;
 margin-left:-1px;
}

#popup_window{
 display:none;
 border:12px solid #292929;
 padding:12px;
 border-radius:12px;
 width:591px;
 min-height:250px;
 overflow:hidden;
 word-wrap: break-word;
 position:absolute;
 _position:absolute;
 z-index:9999;
 background-color:#FFFFFF;
 background-image: -webkit-gradient(
  linear,
  left bottom,
  left top,
  color-stop(0.44, #EDEDED),
  color-stop(0.72, #FFFFFF),
  color-stop(0.86, #FFFFFF)
 );
 background-image: -moz-linear-gradient(
  center bottom,
  #EDEDED 44%,
  #FFFFFF 72%,
  #FFFFFF 86%
 );
 -ms-filter: "progid:DXImageTransform.Microsoft.gradient(GradientType=0, startColorstr=#FFFFFF, endColorstr=#EDEDED)";
 background-image: -o-linear-gradient(#FFFFFF,#EDEDED);
 -moz-box-shadow: 0 0 5px 5px #888;
 -webkit-box-shadow: 0 0 5px 5px#888;
 box-shadow: 0 0 5px 5px #888;
}
.loader{
 display:none;
 font-family:Tahoma;
 font-size:20px;
 width:150px;
 height:150px;
 text-align:center;
 margin:0 auto;
 margin-top:20%;
}
.popup_content_data{
 display:none;
 float:left;
 width:100%;
}
.popup_content_sign_in,.popup_content_sign_up,.popup_content_recoverpass,.popup_content_activate_account,.popup_content_resent_activation_code{
 margin:0 auto;
 margin-left:3px;
 margin-top:5px;
 width:395px;
 padding:5px 5px 11px;
 float:left;
    border-bottom: 1px solid #CCCCCC;
    border-top: 1px solid #CCCCCC;
 min-height:325px;
 display:none;
}
.popup_content_sign_in label,.popup_content_sign_up label,.popup_content_recoverpass label,.popup_content_activate_account label,.popup_content_resent_activation_code label{
 display:block;
 width:125px;
 float:left;
 height:20px;
 padding-top:5px;
 padding-left:3px;
}
.popup_window_close{
 background-image: url('images/close.png');
 width:24px;
 height:24px;
 float:right;
 cursor:pointer;
}
.popup_header_title{
 margin:0 auto;
 width:365px;
 padding:0;
 font-family:Tahoma;
}
.actions_header_title{
 display:inline-block;
 text-align:center;
 font-size:20px;
 padding-bottom:3px;
 margin-bottom:15px;
}
.user_profile_details{
 float:left;
 width: 558px;
 margin-top:15px;
 margin-left:139px;
}
.user_profile_details label{
 float:left;
 margin-top:3px;
 padding-top:2px;
 height:20px;
 width:300px;
}
#user_settings_gender{
 float:left;
 width:257px;
}
#user_page_username{
 float:right;
}
#bg_color{
 display:none;
 position:fixed;
 _position:absolute;
 height:100%;
 width:100%;
 top:0;
 left:0;
 background:#000000;
 border:1px solid #cecece;
 z-index:1;
}
#username_input_signin,#user_settings_current_password,#user_settings_retype_password,#user_settings_password,#user_settings_email,#user_settings_lastname,#user_settings_firstname,#user_settings_username,#username_input_signup,#firstname_input_signup,#lastname_input_signup,#password_input_signin,#password_input_signup,#retype_password_input_signup,#email_input_signup,#email_input_recpass,#email_input_activateaccount,#code_input_activateaccount,#email_input_resent_activation_code{
 border:1px solid #CCC;
 border-radius:5px;
 height:20px;
 width:250px;
 padding:3px;
 margin-bottom:5px;
 float:left;
}
#username_input_signup:hover{
 border:1px solid #000000;
}
#username_input_signin:focus,#user_settings_current_password:focus,#user_settings_retype_password:focus,#user_settings_password:focus,#user_settings_email:focus,#user_settings_lastname:focus,#user_settings_firstname:focus,#user_settings_username:focus,#username_input_signup:focus,#firstname_input_signup:focus,#lastname_input_signup:focus,#password_input_signin:focus,#password_input_signup:focus,#retype_password_input_signup:focus,#email_input_signup:focus,#email_input_recpass:focus,#email_input_activateaccount:focus,#email_input_resent_activation_code:focus,#code_input_activateaccount:focus{
 -moz-box-shadow: 0 0 3px 3px #FFDB2C;
 -webkit-box-shadow: 0 0 3px 3px #FFDB2C;
 box-shadow: 0 0 3px 3px #FFDB2C;
 border:1px solid #A68323;
}
#gender_input_signup{
 width:120px;
}
.popup_right_message{
    background-color: #FFE16B;
    border-radius: 5px 5px 5px 5px;
    float: right;
    padding: 5px;
    width: 170px;
 margin-top:11px;
}

</style>
</head>
<body>
<div id="bg_color"></div>
  <div style="text-align: center;">
   <div id="user_controls">
   
   <div class="signup_popup_button" id="sign_up" title="Sign up">Sign Up</div>
   
   </div>
  </div>
    <div id="popup_window">
   <div class="loader"><img src="images/loading.gif" style="border:0;" alt="loading" />Loading...</div>
   <div class="popup_content_data">
    <span class="popup_window_close" title="Close Popup"></span>
    <h1>Sign Up</h1>
      
    <div class="popup_content_sign_up" style="display:inline-block;">
   <label for="username_input_signup">
    Username:
   </label>
   <input type="text" id="username_input_signup" />
   <br />
   <label for="firstname_input_signup">
    Firstname:
   </label>
   <input type="text" id="firstname_input_signup" />
   <br />
   <label for="lastname_input_signup">
    Lastname:
   </label>
   <input type="text" id="lastname_input_signup" />
   <br />
   <label for="password_input_signup">
    Password:
   </label>
   <input type="password" id="password_input_signup" />
   <br />
   <label for="retype_password_input_signup">
    Re-type Password:
   </label>
   <input type="password" id="retype_password_input_signup" />
   <br />
   <label for="email_input_signup">
    Email:
   </label>
   <input type="text" id="email_input_signup" />
   <br />
   <label for="gender_input_signup">
    Gender:
   </label>
   <select name="gender_input_signup" id="gender_input_signup">
    <option name="0">Select Gender:</option>
    <option name="1">Male</option>
    <option name="2">Female</option>
   </select>
   <br />
   <div id="signup_submit">Sign up</div><br />
   <div class="message_error"></div>
  </div>
   
    
     </div>
  </div>
  </body>
</html>

Saturday, August 17, 2013

Create Database Table Using Class PHP

Create Database Table Using Class PHP

<?php
error_reporting(0);
define('MYSQL_HOSTNAME',  'localhost');  
define('MYSQL_USERNAME',  'root');      
define('MYSQL_PASSWORD',  '');   
define('MYSQL_DATABASE',  'test'); 
define('USERS_TABLE_NAME','alm_users2');

class Db  {
  function connect() {
       $connect      = mysql_connect(MYSQL_HOSTNAME, MYSQL_USERNAME, MYSQL_PASSWORD);
	   $select_db    = mysql_select_db (MYSQL_DATABASE, $connect); 
		if (!$connect) {
		   $errno  = mysql_errno();
		   switch($errno) {
		      case 1045 : { $this->error(); break; }
		    }
		}
		elseif(!$select_db) {$this->error(); break;}
		$strSQL = "SELECT * from ".USERS_TABLE_NAME." limit 1";
        $result = mysql_query ($strSQL); 
		if($result==null) {
		   $this->create_table();
		   die();
		}
   }
   function error() {
        echo "<div style='width:350;margin:auto;text-align:center;font-family:Arial'>
			     <span style='font-size:15px;color:red'>MYSQL SERVER ERROR : ".mysql_error()."</span> 	
			  </div>";
		echo "<div style='width:350;margin:auto;text-align:center;margin-top:10px;font-family:Arial'>
				 You must edit first the database config
			  </div>";	  
	    die();
   }
   function create_table() {
      $strSQL = " CREATE TABLE `".USERS_TABLE_NAME."` (
					  `id` int(11) NOT NULL AUTO_INCREMENT,
					  `username` varchar(200) NOT NULL DEFAULT '',
					  `password` varchar(200) DEFAULT NULL,
					   PRIMARY KEY (`id`)
				   )   ENGINE=MyISAM DEFAULT CHARSET=utf8;
	            ";
      $result = mysql_query ($strSQL); 
	  $strSQL = "INSERT INTO `".USERS_TABLE_NAME."` (`id`,`username`,`password`) VALUES (1,'admin','admin');";
	  $result = mysql_query ($strSQL); 
	  echo ('<meta http-equiv="refresh" content="0;">');
   }
	 
	  
 }  
 
$msql  = new Db;
$msql->connect();
?> 

Ajax, Php class dynamic select box

Ajax, Php class dynamic select box 

Create table state

CREATE TABLE IF NOT EXISTS `state` (
  `state_id` int(11) NOT NULL AUTO_INCREMENT,
  `country_id` int(11) NOT NULL,
  `state_name` varchar(255) NOT NULL,
  PRIMARY KEY (`state_id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;

INSERT INTO `state` (`state_id`, `country_id`, `state_name`) VALUES
(1, 98, 'Zambales'),
(2, 98, 'Pampanga');

Crate table city

CREATE TABLE IF NOT EXISTS `city` (
  `city_id` bigint(20) NOT NULL AUTO_INCREMENT,
  `state_id` bigint(20) NOT NULL,
  `country_id` int(11) NOT NULL,
  `city_name` varchar(255) NOT NULL,
  PRIMARY KEY (`city_id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;

INSERT INTO `city` (`city_id`, `state_id`, `country_id`, `city_name`) VALUES
(1, 1, 98, 'Olongapo City'),
(2, 1, 98, 'Iba'),
(3, 2, 98, 'Angeles City'),
(4, 2, 98, 'San Fernando');

//index.php
<?php
	include("functions.php");		
	$db = new PHP_fun();
?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Ajax, Php class list box </title>
<script language="javascript"  type="text/javascript" src="validation.js"></script>
<script language="javascript" type="text/javascript">
	function getCities(id)
	{
		var obj = document.form1;
		if (id != "")
		{
			url = "getCities.php?stateid="+id;
			http.open("GET", url, true);
			http.onreadystatechange = getCitiesResponse; 
			http.send(null);
		}
	}
	
	function getCitiesResponse()
	{
		//alert(http.readyState);
		var obj = document.form1;
		if (http.readyState == 4)
		{
			var result = trimString(http.responseText);
			if (result != '' && result != 'undefined')
			{
				clearBox(obj.city);
				obj.city.options[0] = new Option("-City-", "");
				var result_line_arr = result.split("###");
				for (i=0;i<result_line_arr.length;i++)
				{
					var result_arr = result_line_arr[i].split(":");
					var code = result_arr[0];
					var name = result_arr[1];
					obj.city.options[i+1] = new Option(name, code);
				}
			}		
		}
	}
</script>
</head>
<body>
<table width="60%" border="0" cellspacing="0" cellpadding="5">
<form action="" method="post" name="form1">
  <tr>
      <td align="right" class="verdana11">State :</td>
      <td align="left" class="verdana11">
      	<select name="state" id="state" onchange="javascript: getCities(this.value);">
        	<option value="">-State-</option>
            <?php
				$sql = "select * from state";
				$rs = $db->select_row($sql);
				for($i=0;$i<count($rs);$i++)
				{ ?>
					<option value="<?=$rs[$i]['state_id']?>"><?=$rs[$i]['state_name']?></option>
				<?php }
            ?>
        </select>     
	</td>
  </tr>
    <tr>
      <td align="right" class="verdana11">City : </td>
      <td align="left" class="verdana11">
		  <select name="city" id="city" style="width:150px;">
				<option value="">-City-</option>
		  </select>      
	  </td>
    </tr>
</form>
</table>
</body>
</html>
//funtion.php
<?php
	class PHP_fun 
	{
		function getConfig()
		{
			$this->DB_SERVER = 'localhost'; 
			$this->DB_USER = 'root'; 
			$this->DB_PASS = ''; 
			$this->DB_NAME = 'test'; 
		
		}
		function __construct()
		{
			$this->getConfig();
			$Conn = mysql_connect($this->DB_SERVER, $this->DB_USER, $this->DB_PASS);
			if (!$Conn)
				die("Error: ".mysql_errno($Conn).":- ".mysql_error($Conn));
			$DB_select = mysql_select_db($this->DB_NAME, $Conn);
			if (!$DB_select)
				die("Error: ".mysql_errno($Conn).":- ".mysql_error($Conn));
		}

		function select_row($sql)
		{
			if ($sql!="")
			{
				$result = mysql_query($sql) or die("Error: ".mysql_errno().":- ".mysql_error());
				if ($result)
				{
					while($row = mysql_fetch_array($result))
						$data[] = $row;
				}
				return $data;
			}
		}
	}
?>	
//getCities.php
<?php
	include("functions.php");		
	$db = new PHP_fun();
	$str = "";
	$stateid = trim($_REQUEST['stateid']);
	if ($stateid != "")
	{
		$sql = sprintf("SELECT city_id, city_name FROM city WHERE state_id = '%d' ", $stateid);
		$rs = $db->select_row($sql);
		if (count($rs) > 0)
		{
			for($i=0;$i<count($rs);$i++)
			{
				$str .=  $rs[$i]['city_id'].":".$rs[$i]['city_name']."###";
			}
			echo $str = substr($str,0,-3);
		}
	}
?>
//validation.js
// ajax oject 
		function getHTTPObject() 
		{ 
			var xmlhttp; 
			/*@cc_on @if (@_jscript_version >= 5) try { xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } catch (E) { xmlhttp = false; } } @else xmlhttp = false; @end @*/  
			if (!xmlhttp && typeof XMLHttpRequest != 'undefined') 
			{ 
				try { 
					xmlhttp = new XMLHttpRequest(); 
				} 
				catch (e) { 
					xmlhttp = false; 
				} 
			} 
			return xmlhttp;
		}
		var http = getHTTPObject(); // We create the HTTP Object 
		
		function clearBox(ObjselBox)	
		{
			for(i=ObjselBox.length-1; i>=0; i--)
			{
				deleteOption(ObjselBox, i);
			}
		}
		
		function deleteOption(theSel, theIndex)
		{	
			var selLength = theSel.length;
			if(selLength > 0)
			{
				theSel.options[theIndex] = null;
			}
		}
		
		// end ajas object
		
		
		function trimString(str)
		{
			return str.replace(/^\s+|\s+$/g, '');
		}

Simple PHP Class Drop Down Menu

Simple PHP Class Drop Down Menu 

Create database table

CREATE TABLE `tblcategories` (
  `id` int(11) NOT NULL,
  `Name` varchar(100) collate latin1_general_ci NOT NULL,
  `pid` int(11) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci;


//index.php
<?php
DEFINE ('DB_USER', 'root');
DEFINE ('DB_PASSWORD', '');
DEFINE ('DB_HOST', 'localhost');
DEFINE ('DB_NAME', 'test');

class AjaxDropdown
{
	var $table;
	function AjaxDropdown()
	{		
		mysql_connect (DB_HOST, DB_USER, DB_PASSWORD) OR die ('Could not connect to MySQL: ' . mysql_error() );
		mysql_select_db (DB_NAME) OR die ('Could not select the database: ' . mysql_error() );
		$this->table = "tblcategories";
	}
	
	function dbConnect()
	{
		mysql_connect (DB_HOST, DB_USER, DB_PASSWORD);
	}
		
	
	function getArray($id)
	{
		$this->dbConnect();
		$query = "SELECT * FROM $this->table where pid = {$id} ORDER BY id asc";
		$result = mysql_query ($query);
		$arr = array();
		while($row = mysql_fetch_object($result))
		{
			$arr[] = $row;
		}
		mysql_close();		
		return $arr;	
	}
}

$strRet = "";
$obj = new AjaxDropdown();
$arr = $obj->getArray(0);
$strRet .= '<option value="0">--Select--</option>';
foreach ( $arr as $row )
{
	$strRet .= '<option value="'.$row->id.'">'.$row->Name.'</option>';
}
?>
<select name="selCat" class="text">
	<?php echo $strRet; ?>
</select>

Ajax Add & Delete MySQL records using jQuery & PHP

Ajax Add & Delete MySQL records using jQuery & PHP 

Create Table

CREATE TABLE IF NOT EXISTS `add_delete_record` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `content` text NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
//index.php
<html>
<head>
<title>Ajax Add/Delete Record with jQuery</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
	$("#FormSubmit").click(function (e) {
			e.preventDefault();
			if($("#contentText").val()==='')
			{
				alert("Please enter some text!");
				return false;
			}
		 	var myData = 'content_txt='+ $("#contentText").val(); //build a post data structure
			jQuery.ajax({
			type: "POST", // Post / Get method
			url: "response.php", //Where form data is sent on submission
			dataType:"text", // Data type, HTML, json etc.
			data:myData, //Form variables
			success:function(response){
				$("#responds").append(response);
				$("#contentText").val(''); 
			},
			error:function (xhr, ajaxOptions, thrownError){
				alert(thrownError);
			}
			});
	});

	$("body").on("click", "#responds .del_button", function(e) {
		 e.returnValue = false;
		 var clickedID = this.id.split('-'); //Split string (Split works as PHP explode)
		 var DbNumberID = clickedID[1]; //and get number from array
		 var myData = 'recordToDelete='+ DbNumberID; //build a post data structure
		 
			jQuery.ajax({
			type: "POST", // Post method
			url: "response.php", 
			dataType:"text", // Data type, HTML, json etc.
			data:myData, //Form variables
			success:function(response){
				$('#item_'+DbNumberID).fadeOut("slow");
			},
			error:function (xhr, ajaxOptions, thrownError){
				//On error, we alert user
				alert(thrownError);
			}
			});
	});
});
</script>
<link href="css/style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="content_wrapper">
<ul id="responds">
<?php
include_once("config.php");
//MySQL query
$Result = mysql_query("SELECT id,content FROM add_delete_record");
//get all records from add_delete_record table
while($row = mysql_fetch_array($Result))
{
  echo '<li id="item_'.$row["id"].'">';
  echo '<div class="del_wrapper"><a href="#" class="del_button" id="del-'.$row["id"].'">';
  echo '<img src="images/icon_del.gif" border="0" />';
  echo '</a></div>';
  echo $row["content"].'</li>';
}
mysql_close($connecDB);
?>
</ul>
    <div class="form_style">
    <textarea name="content_txt" id="contentText" cols="45" rows="5"></textarea>
    <button id="FormSubmit">Add record</button>
    </div>
</div>
</body>
</html>
//config.php
<?php
$username = "root"; 
$password = ""; 
$hostname = "localhost";
$databasename = 'test';
$connecDB = mysql_connect($hostname, $username, $password)or die('could not connect to database');
mysql_select_db($databasename,$connecDB);
?>
response.php
<?php
include_once("config.php");
if(isset($_POST["content_txt"]) && strlen($_POST["content_txt"])>0) 
{	
	/* 
	sanitize post value, PHP filter FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH
	Strip tags, encode special characters.
	*/
	$contentToSave = filter_var($_POST["content_txt"],FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH); 
	if(mysql_query("INSERT INTO add_delete_record(content) VALUES('".$contentToSave."')"))
	{
		  $my_id = mysql_insert_id(); 
		  echo '<li id="item_'.$my_id.'">';
		  echo '<div class="del_wrapper"><a href="#" class="del_button" id="del-'.$my_id.'">';
		  echo '<img src="images/icon_del.gif" border="0" />';
		  echo '</a></div>';
		  echo $contentToSave.'</li>';
	}else{
		header('HTTP/1.1 500 Looks like mysql error, could not insert record!');
		exit();
	}
}
elseif(isset($_POST["recordToDelete"]) && strlen($_POST["recordToDelete"])>0 && is_numeric($_POST["recordToDelete"]))
{	
	$idToDelete = filter_var($_POST["recordToDelete"],FILTER_SANITIZE_NUMBER_INT); 
	if(!mysql_query("DELETE FROM add_delete_record WHERE id=".$idToDelete))
	{    
		header('HTTP/1.1 500 Could not delete record!');
		exit();
	}
}
else
{
	//Output error
	header('HTTP/1.1 500 Error occurred, Could not process request!');
    exit();
}
mysql_close($connecDB);
?>

Thursday, August 15, 2013

Simple Class login using php

Simple Class login using php 
 
<?
class UserAuth {
 var $user;
 var $pass;
 function isUserValid($user, $pass) {
  $sql = "select uid, first_name from $users_tb where user_name='$user' and password='$pass'";
  $result = mysql_query($sql);
  $rows   = mysql_num_rows($result);
  if($rows == 1) {
   $result_row = mysql_fetch_row($result);
   return $result_row;
  }
  else {
   return "0";
  }
 }
}
$userauth = new UserAuth;

session_start();
$user = $_POST['uname'];
$pass = $_POST['password'];
$val = $userauth->isUserValid($user, $pass);
if($val == "0") {
 header("Location: login.php");
}
else {
 $_SESSION['uid'] = $val[0];
 $_SESSION['fname'] = $val[1];
 $_SESSION['uname'] = $user;
 header("Location: SchedulerMain.php");
}
?>
<form name="scheduler_login" method="post" action="UserAuthController.php">
User name<input type=text size=15 name=uname>
Password<input type=password size=15 name=password>
<input type=submit name=submit value="Submit"> 
</form>

Sunday, August 11, 2013

Jquery Count Remaining Character

Jquery Count Remaining Character

 
<script type="text/javascript" src="js/jquery-1.9.0.min.js"></script><script>
$(document).ready(function(){
 var totalChars   = 100; //Total characters allowed in textarea
 var countTextBox  = $('#counttextarea') // Textarea input box
 var charsCountEl  = $('#countchars'); // Remaining chars count will be displayed here
 charsCountEl.text(totalChars); //initial value of countchars element
 countTextBox.keyup(function() { //user releases a key on the keyboard
  var thisChars = this.value.replace(/{.*}/g, '').length; //get chars count in textarea
  var per = thisChars*100; 
  var value= (per / totalChars); // total percent complete
  if(thisChars > totalChars) //if we have more chars than it should be
  {
   var CharsToDel = (thisChars-totalChars); // total extra chars to delete
   this.value = this.value.substring(0,this.value.length-CharsToDel); //remove excess chars from textarea
  }else{
   charsCountEl.text( totalChars - thisChars ); //count remaining chars
   $('#percent').text(value +'%');
  }
 }); 
});
</script>

<div class="main-item"><div><textarea name="counttextarea" id="counttextarea" cols="45" rows="5" style="width: 400px;padding: 10px;"></textarea></div>
<div><span name="countchars" id="countchars"></span> Characters Remaining. <span name="percent" id="percent"></span></div>
</div>

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

Related Post