article

Tuesday, June 18, 2013

Validate password strength using jQuery

Validate password strength using jQuery

 
<style type="text/css">
#register {
    margin-left:100px;
}
 #register label{
    margin-right:5px;
}
 #register input {
    padding:5px 7px;
    border:1px solid #d5d9da;
    box-shadow: 0 0 5px #e8e9eb inset;
    width:250px;
    font-size:1em;
    outline:0;
}
 #result{
    margin-left:5px;
}
 #register .short{
    color:#FF0000;
}
 #register .weak{
    color:#E66C2C;
}
 #register .good{
    color:#2D98F3;
}
 #register .strong{
    color:#006400;
}
 </style>
<script type="text/javascript" src="jquery.js"></script>
<script>
$(document).ready(function() {
  
    $('#password').keyup(function(){
        $('#result').html(checkStrength($('#password').val()))
    }) 
  
    function checkStrength(password){
  
    //initial strength
    var strength = 0
  
    //if the password length is less than 6, return message.
    if (password.length < 6) {
        $('#result').removeClass()
        $('#result').addClass('short')
        return 'Too short'
    }
  
    //length is ok, lets continue.
  
    //if length is 8 characters or more, increase strength value
    if (password.length > 7) strength += 1
  
    //if password contains both lower and uppercase characters, increase strength value
    if (password.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/))  strength += 1
  
    //if it has numbers and characters, increase strength value
    if (password.match(/([a-zA-Z])/) && password.match(/([0-9])/))  strength += 1
  
    //if it has one special character, increase strength value
    if (password.match(/([!,%,&,@,#,$,^,*,?,_,~])/))  strength += 1
  
    //if it has two special characters, increase strength value
    if (password.match(/(.*[!,%,&,@,#,$,^,*,?,_,~].*[!,",%,&,@,#,$,^,*,?,_,~])/)) strength += 1
  
    //now we have calculated strength value, we can return messages
  
    //if value is less than 2
    if (strength < 2 ) {
        $('#result').removeClass()
        $('#result').addClass('weak')
        return 'Weak'
    } else if (strength == 2 ) {
        $('#result').removeClass()
        $('#result').addClass('good')
        return 'Good'
    } else {
        $('#result').removeClass()
        $('#result').addClass('strong')
        return 'Strong'
    }
}
});
</script>
 <form id="register">
    <label for="password">Password:</label>
    <input name="password" id="password" type="password"/>
    <span id="result"></span>
</form>

Form validations with Javascript and HTML5

Form validations with Javascript and HTML5


Javascript Form

<script type="text/javascript">
function send(){
if(document.dataform.tx_name.value=="" || document.dataform.tx_name.value.length < 8)
{
alert( "Insert your name with more than 8 chars!" );
document.dataform.tx_name.focus();
return false;
}
if( document.dataform.tx_email.value=="" || document.dataform.tx_email.value.indexOf('@')==-1 || document.dataform.tx_email.value.indexOf('.')==-1 )
{
alert( "Insert an valid e-mail adress!" );
document.dataform.tx_email.focus();
return false;
}
if (document.dataform.tx_message.value=="")
{
alert( "Insert your message!" );
document.dataform.tx_message.focus();
return false;
}
if (document.dataform.tx_message.value.length < 50 )
{
alert( "Is necessary to use more than 50 chars in the message field!" );
document.dataform.tx_message.focus();
return false;
}
return true;
}
</script>
<form action="#" method="post" name="dataform" onSubmit="return send();" >
  <table width="588" border="0" align="center" >
    <tr>
      <td width="118"><font size="1" face="Verdana, Arial, Helvetica, sans-serif">Name:</font></td>
      <td width="460">
        <input name="tx_name" type="text" class="formbutton" id="tx_name" size="52" maxlength="150">
      </td>
    </tr>
    <tr>
      <td><font size="1" face="Verdana, Arial, Helvetica, sans-serif">E-mail:</font></td>
      <td><font size="2">
        <input name="tx_email" type="text" id="tx_email" size="52" maxlength="150" class="formbutton">
      </font></td>
    </tr>
    <tr>
      <td><font face="Verdana, Arial, Helvetica, sans-serif"><font size="1">Message<strong>:</strong></font></font></td>
      <td rowspan="2"><font size="2">
        <textarea name="tx_message" cols="50" rows="8" class="formbutton" id="tx_message" input ></textarea>
      </font></td>
    </tr>
    <tr>
      <td height="85"><p><strong><font face="Verdana, Arial, Helvetica, sans-serif"><font size="1">
      </font></font></strong></p></td>
    </tr>
    <tr>
      <td height="22"></td>
      <td>
        <input name="Submit" type="submit"  class="formobjects" value="Send">
  
        <input name="Reset" type="reset" class="formobjects" value="Reset">
      </td>
    </tr>
  </table>
</form>   
HTML 5 Form
<form method="post" action="">
    <label for="name">Name: </label>
    <input id="name" type=text required name=name/>
<br />
    <label for="email">Email: </label>
    <input id="email" type=text required name=email/>
<input type=submit value="OK"/>
</form> 

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>

Friday, June 14, 2013

Create a simple style css table

Create a simple style css table



 
<style>
.simple-style {border-top:1px solid #CFCFCF; border-left:1px solid #CFCFCF; border-right:0; border-bottom:0; width:100%;font-family: Arial, Helvetica, tahoma sans-serif; font-size:12px; line-height:1.6; color:#282828;}
.simple-style td, .simple-style th {border-right:1px solid #CFCFCF; border-bottom:1px solid #CFCFCF; text-align:center; padding:5px 0; width:20%;}
.simple-style th {background-color:#dedede; font-size:120%;text-shadow: 0 1px 0 #fff;}
.simple-style tr:nth-child(even) {background: #fff;}
.simple-style tr:nth-child(odd) {background: #F6F6F6;}
</style>
<div style="width:700px;">
<h3>SIMPLE STYLE TABLE</h3>
<table class="simple-style">
    <thead>
        <tr>
            <th scope="col">Country</th>
            <th scope="col">Area</th>
            <th scope="col">Official languages</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>United States of America</td>
            <td>9,826,630 km2</td>
            <td>English</td>
        </tr>
        <tr>
            <td>United Kingdom</td>
            <td>244,820 km2</td>
            <td>English</td>
        </tr>
        <tr>
            <td>India</td>
            <td>3,287,240 km2</td>
            <td>Hindi, English</td>
        </tr>
        <tr>
            <td>Canada</td>
            <td>9,984,670 km2</td>
            <td>English, French</td>
        </tr>
        <tr>
            <td>Germany</td>
            <td>357,021 km2</td>
            <td>German</td>
        </tr>
    </tbody>
</table>
</div>

CSS3 Techniques

CSS3 Techniques







 
<style type="text/css">
body {
 background-color: #D6E4FF;
}

.shadow1 {
 background-color: #eee; 
 padding: 10px;
 padding-left: 18px;
 padding-right: 18px;
 box-shadow: 0px 2px 4px rgba(0,0,0,0.7);
 -webkit-box-shadow: 0px 2px 4px rgba(0,0,0,0.7);
 -moz-box-shadow: 0px 2px 4px rgba(0,0,0,0.7);
 color: black;
 font-family: "Lucida Sans MS", "Lucida Grande", Helvetica, sans-serif;
 font-size: 10pt;
}
.shadow2 {
 background-color: #333; 
 padding: 10px;
 padding-left: 18px;
 padding-right: 18px;
 box-shadow: 0px 2px 6px rgba(255,255,153,0.7);
 -webkit-box-shadow: 0px 2px 6px rgba(255,255,153,0.7);
 -moz-box-shadow: 0px 2px 6px rgba(255,255,153,0.7);
 color: white;
 font-family: "Lucida Sans MS", "Lucida Grande", Helvetica, sans-serif;
 font-size: 10pt;
}


.round1 {
 background-color: #f99;
 border: solid 1px black;
 border-radius: 6px;
 -webkit-border-radius: 6px;
 -moz-border-radius: 6px;
 padding: 10px;
 padding-left: 18px;
 padding-right: 18px;
 color: black;
 font-family: "Lucida Sans MS", "Lucida Grande", Helvetica, sans-serif;
 font-size: 10pt;
}
.round2 {
 background-color: #333; 
 border-radius: 12px;
 -webkit-border-radius: 12px;
 -moz-border-radius: 12px;
 -webkit-border-top-left-radius: 59px 20px;
 -webkit-border-bottom-left-radius: 59px 20px;
 -moz-border-radius-topleft: 59px 20px;
 -moz-border-radius-bottomleft: 59px 20px;
 padding: 10px;
 padding-left: 18px;
 padding-right: 18px;
 color: white;
 font-family: "Lucida Sans MS", "Lucida Grande", Helvetica, sans-serif;
 font-size: 10pt;
}
.round3 {
 border: dashed 2px #093;
 -webkit-border-top-left-radius: 17px;
 -moz-border-radius-topleft: 17px;
 -webkit-border-bottom-right-radius: 17px;
 -moz-border-radius-bottomright: 17px;
 background-color: #ff9; 
 padding: 10px;
 padding-left: 18px;
 padding-right: 18px;
 color: black;
 font-family: "Lucida Sans MS", "Lucida Grande", Helvetica, sans-serif;
 font-size: 10pt;
}



.css5box2 {
 <!-- Baseline -->
 
 background-color: #fed; 
 border-top: solid 1px white;
 border-bottom: solid 1px #669;
 padding: 10px;
 padding-left: 18px;
 padding-right: 18px;
 color: black;
 font-family: "Lucida Sans MS", "Lucida Grande", Helvetica, sans-serif;
 font-size: 10pt;
 margin-bottom: 10px;
 border-radius: 8px;
 <!-- border radius -->
 -webkit-border-radius: 8px;
 -moz-border-radius: 8px;
 <!-- shadows -->
 -moz-border-radius: 8px;
 box-shadow: 0px 1px 3px rgba(0,0,0,0.7);
 -webkit-box-shadow: 0px 1px 3px rgba(0,0,0,0.7);
 -moz-box-shadow: 0px 1px 3px rgba(0,0,0,0.7);
 <!-- gradient -->
 background: -webkit-gradient(
            linear,
            center top, center bottom,
            color-stop(0%, #fffffa),
            color-stop(30%, #fed),
            color-stop(80%, #fed),
            color-stop(100%, #fffffa)
          );
 background: -moz-linear-gradient(
            top, #eef, #cce 30%, #cce 80%, #eef 100%
          );
 width:350px;   
}

.gradback {
 background-color: #eee; 
 background: -webkit-gradient(
            linear,
            center top, center bottom,
            color-stop(0%, #eef),
            color-stop(30%, #cce),
            color-stop(80%, #cce),
            color-stop(100%, #eef)
          );
 background: -moz-linear-gradient(
            top, #eef, #cce 30%, #cce 80%, #eef 100%
          );

 border-top: solid 1px white;
 border-bottom: solid 1px #669;
 padding: 10px;
 padding-left: 18px;
 padding-right: 18px;
 border-radius: 8px;
 -webkit-border-radius: 8px;
 -moz-border-radius: 8px;
 box-shadow: 0px 1px 3px rgba(0,0,0,0.7);
 -webkit-box-shadow: 0px 1px 3px rgba(0,0,0,0.7);
 -moz-box-shadow: 0px 1px 3px rgba(0,0,0,0.7);
 color: black;
 font-family: "Lucida Sans MS", "Lucida Grande", Helvetica, sans-serif;
 font-size: 10pt;
}
.css5box2 h3 {
 text-shadow: 0px 3px 3px rgba(0,0,0,0.2);
 color: #339;
}

input.styled {
 background-color: #eee; 
 background: -webkit-gradient(
            linear,
            center top, center bottom,
            color-stop(0%, #eee),
            color-stop(100%, #fff)
          );
 background: -moz-linear-gradient(
            top, #eee, #fff
          );

 border: solid 2px white;
 padding: 3px;
 padding-left: 7px;
 padding-right: 7px;
 border-radius: 4px;
 -webkit-border-radius: 4px;
 -moz-border-radius: 4px;
 box-shadow: 0px 1px 3px rgba(0,0,0,0.7);
 -webkit-box-shadow: 0px 1px 3px rgba(0,0,0,0.7);
 -moz-box-shadow: 0px 1px 3px rgba(0,0,0,0.7);
 color: black;
 text-shadow: 0px 1px 1px white;
 font-family: "Lucida Sans MS", "Lucida Grande", Helvetica, sans-serif;
 font-size: 10pt;
}
input.styled:focus {
 box-shadow: 0px 1px 6px rgba(0,64,255,0.7);
 -webkit-box-shadow: 0px 1px 6px rgba(0,64,255,0.7);
 -moz-box-shadow: 0px 1px 6px rgba(0,64,255,0.7);
 outline: none;
 -webkit-focus-ring-color: none;
}

input.roundbutton {
 background-color: #eee; 
 background: -webkit-gradient(
            linear,
            center top, center bottom,
            color-stop(0%, #eee),
            color-stop(100%, #ccc)
          );
 background: -moz-linear-gradient(
            top, #eee, #ccc
          );

 border: solid 2px white;
 padding: 10px;
 padding-left: 18px;
 padding-right: 18px;
 border-radius: 8px;
 -webkit-border-radius: 8px;
 -moz-border-radius: 8px;
 cursor: pointer;
 box-shadow: 0px 1px 3px rgba(0,0,0,0.7);
 -webkit-box-shadow: 0px 1px 3px rgba(0,0,0,0.7);
 -moz-box-shadow: 0px 1px 3px rgba(0,0,0,0.7);
 color: black;
 text-shadow: 0px 1px 1px white;
 font-family: "Lucida Sans MS", "Lucida Grande", Helvetica, sans-serif;
 font-size: 10pt;
}
input.roundbutton:active {
 border-width: 1px;
 margin-left: 1px;
 margin-right: 1px;
 -box-shadow: 0px 1px 1px rgba(0,0,0,0.8);
 -webkit-box-shadow: 0px 1px 1px rgba(0,0,0,0.8);
 -moz-box-shadow: 0px 1px 1px rgba(0,0,0,0.8);
 background: -webkit-gradient(
            linear,
            center top, center bottom,
            color-stop(100%, #eee),
            color-stop(0%, #ccc)
          );
 background: -moz-linear-gradient(
            top, #ccc, #eee
          );

}
</style>
<p><b>Shadows</b></p>
<p> <span class="shadow1">Shadow</span>   <span class="shadow2">Glow</span></p>
<p><b>Borders with Rounded Corners</b></p>
<p> <span class="round1">Round Corners</span>   <span class="round2">Round Corners</span>   <span class="round3">Round Corners</span></p>

<p><b>How to Style Boxes</b></p>
<div class="css5box2">
<h3>Lorem Ipsum Dolor</h3>
<p>Lorem ipsum dolor sit amet,  vurucelerisque tincidunt ac vel elit.</p>
</div>

<div>
<input type="text" value="I am a text field" size="43" class="styled" />
</div>

<p><b>Styling Forms</b></p>
<div style="height: 43px">
<input type="button" value="Click Me" class="roundbutton" />
</div>

Create CSS Testimonial

Create CSS Testimonial
<style>
.testimonial {
    margin: 0;
    background: #B7EDFF;
    padding: 10px 50px;
    position: relative;
    font-family: Georgia, serif;
    color: #666;
    border-radius: 5px;
    font-style: italic;
    text-shadow: 0 1px 0 #ECFBFF;
    background-image: linear-gradient(#CEF3FF, #B7EDFF);
 width:400px;
}

.testimonial:before, .testimonial:after {
    content: "\201C";
    position: absolute;
    font-size: 80px;
    line-height: 1;
    color: #999;
    font-style: normal;
}

.testimonial:before {
    top: 0;
    left: 10px;
}
.testimonial:after {
    content: "\201D";
    right: 10px;
    bottom: -0.5em;
}
.arrow-down {
    width: 0;
    height: 0;
    border-left: 15px solid transparent;
    border-right: 15px solid transparent;
    border-top: 15px solid #B7EDFF;
    margin: 0 0 0 25px;
}
.testimonial-author {
    margin: 0 0 0 25px;
    font-family: Arial, Helvetica, sans-serif;
    color: #999;
    text-align:left;
}
.testimonial-author span {
    font-size: 12px;
    color: #666;
}
</style>
<blockquote class="testimonial">
  <p>Nullam non wisi a sem semper eleifend. Pellentesque habitant morbi tristique senectus et netus et male</p>
</blockquote>
<div class="arrow-down"></div>
<p class="testimonial-author">adipiscin</span></p>

Sunday, June 9, 2013

Understanding PHP Functions

Understanding PHP Functions 

<?php 
function calculate($num1, $num2, $operation = '+')
{
    switch($operation)
    {
        case '+': // add
            return $num1 + $num2;
            break;
        case '-': // subtract
            return $num1 - $num2;
            break;
        case '*': // multiply
            return $num1 * $num2;
            break;
        case '/': // divide, make sure denominator is not zero
            return ($num2 == 0) ? 'Cannot divide by zero' : $num1 / $num2;
            break;
        default:  // Display error message for unknown operation ex 'a', 'b' etc.
            return 'Unkown Operation Fool!';
            break;
    }
}
?>
<html>
<body>
<?php
    echo '1 + 3 = ';
    echo calculate(1,3);
    echo '<br />';
    echo '9 x 5 = ';
    echo calculate(9,5,'*');
    echo '<br />';
    echo 'Division by zero test: ';
    echo calculate(10, 0, '/');
    echo '<br />';
?>
</body>
</html>

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>

Session Security Tips

Session Security Tips 

Timing-out sessions is a very important action if you are dealing with users logged in to your website or application. If a user logs in to your site in an Internet café and then leaves the computer and café without logging out, how do you stop the next user on that computer from still having access to the previous user’s session?

<?php
session_start();
// set time-out period (in seconds)
$inactive = 600;

// check to see if $_SESSION["timeout"] is set
if (isset($_SESSION["timeout"])) {
    // calculate the session's "time to live"
    $sessionTTL = time() - $_SESSION["timeout"];
    if ($sessionTTL > $inactive) {
        session_destroy();
        header("Location: /logout.php");
    }
}

$_SESSION["timeout"] = time();
?>

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>

Friday, June 7, 2013

Pagination with CodeIgniter

Pagination with CodeIgniter

In this tutorial, I’ll use CodeIgniter’s pagination library to show you how you can create a paginated list of results from a MySQL database.

The Model

models/countries.php

record_count() method returns the number of records and is needed because one of the options in the $config array for the pagination library is $config["total_rows"].
fetch_countries() method retrieves a list of all the records from the Country table. There are two arguments for this method: $limit and $start.


<?php
class Countries extends CI_Model
{
    public function __construct() {
        parent::__construct();
    }

    public function record_count() {
        return $this->db->count_all("Country");
    }

    public function fetch_countries($limit, $start) {
        $this->db->limit($limit, $start);
        $query = $this->db->get("Country");

        if ($query->num_rows() > 0) {
            foreach ($query->result() as $row) {
                $data[] = $row;
            }
            return $data;
        }
        return false;
   }
}
The Controller

controllers/welcome.php
 
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Welcome extends CI_Controller {

 public function __construct() {
        parent:: __construct();
        $this->load->helper("url");
        $this->load->model("Countries");
        $this->load->library("pagination");
  $this->load->library('table');
    }

    public function example1() { 
        $config = array();
        $config["base_url"] = base_url() . "welcome/example1";
        $config["total_rows"] = $this->Countries->record_count();
        $config["per_page"] = 20;
        $config["uri_segment"] = 3;

        $this->pagination->initialize($config);

        $page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
        $data["results"] = $this->Countries->
            fetch_countries($config["per_page"], $page);
        $data["links"] = $this->pagination->create_links();

        $this->load->view("countries_view", $data);
    }
 
 public function index()
 {
  $this->load->view('welcome_message');
 }
}
The View views/countries_view.php
<body>
 <div id="container">
  <h1>Countries</h1>
  <div id="body">
<?php
foreach($results as $data) {
    echo $data->printable_name . " - " . $data->iso3 . "<br>";
}
?>
   <p><?php echo $links; ?></p>
  </div>
  <p class="footer">Page rendered in <strong>{elapsed_time}</strong> seconds</p>
 </div>
</body>
URL: http://yourdomain/welcome/example1

Using jQuery and ajax with Codeigniter

Using jQuery and ajax with Codeigniter

change the ajax url parameter to this:
    url: <?php echo base_url().'profiles/get_all_users';?>
http://www.yourdomain.com/products/get_all_users



<?php
//products controller
class Products extends CI_Controller{
    
    function __construct(){
        parent::__construct();
    }
    
    public function get_all_users(){
 
        $query = $this->db->get('products');
        if($query->num_rows > 0){
            $header = false;
            $output_string = '';
            $output_string .=  "<table border='1'>\n";
            foreach ($query->result() as $row){
                $output_string .= '<tr>\n';
                $output_string .= "<th>{$row['value']}</th>\n";    
                $output_string .= '</tr>\n';                
            }                    
            $output_string .= '</table>\n';
        }
        else{
            $output_string = 'There are no results';
        }
         
        echo json_encode($output_string);
    }
 }
?> 
<html>
<script language='JavaScript' type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js'></script>
<head>
<meta http-equiv='Content-Type' content='text/html; charset=utf-8' />
<title>Display Page</title>
</head>
<body>
<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().'profiles/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>
</body>
</html>

Thursday, June 6, 2013

jQuery Syntax

jQuery Syntax

The jQuery syntax is tailor made for selecting HTML elements and performing some action on the element(s).
Basic syntax is: $(selector).action()
  • A $ sign to define/access jQuery
  • A (selector) to "query (or find)" HTML elements
  • A jQuery action() to be performed on the element(s)
Examples:
$(this).hide() - hides the current element.
$("p").hide() - hides all elements.
$(".test").hide() - hides all elements with class="test".
$("#test").hide() - hides the element with id="test".

Tuesday, June 4, 2013

Zend Framework Database Query

Zend Framework Database Query

Database Manipulation
  • Create a controller
  • Call / Create(Write) Database configuration setting
  • Request data object creation
  • Assign message (Success / Failure / Already exists)
  • Create a view page to see the message or to redirect to the previous page to fill it up again
Controller creation
public function processAction(){
}
Database configuration creation/call from registry
$registry = Zend_Registry::getInstance();
$DB = $registry['DB'];
Or
$params = array(‘host’=>’localhost’ , ‘username’ =>’root’ , ‘password’ =>” , ‘dbname’ =>’zend’ );
$DB = new Zend_Db_Adapter_Pdo_Mysql($params);
Insert Query
$sql = "INSERT INTO `user`
(`first_name` , `last_name` ,`user_name` ,`password`)
VALUES
(‘".$request->getParam(‘first_name’)."’, ‘".$request->getParam(‘last_name’)."’, ‘".$request->getParam(‘user_name’)."’, MD5(‘".$request->getParam(‘password’)."’))";$DB->query($sql);
OR
$data = array(‘first_name’ => $request->getParam(‘first_name’),
‘last_name’ => $request->getParam(‘last_name’),
‘user_name’ => $request->getParam(‘user_name’),
‘password’ => md5($request->getParam(‘password’))
);$DB->insert(‘user’, $data);
Fetch Query
$params = array(‘host’ =>’localhost’, ‘username’ =>’root’, ‘password’ =>”, ‘dbname’ =>’zend’ );
$DB = new Zend_Db_Adapter_Pdo_Mysql($params);$DB->setFetchMode(Zend_Db::FETCH_OBJ);
$sql = "SELECT * FROM `user` ORDER BY user_name ASC";
$result = $DB->fetchAssoc($sql);
$this->view->assign(‘data’,$result); // Send the array to the view page
Access a variable in the view page
$received_data = $this->data; // received the whole data array
Var_dump($ received_data); // print the whole array
?>
Update Query
$params = array(‘host’ =>’localhost’, ‘username’ =>’root’, ‘password’ =>”, ‘dbname’ =>’zend’ );
$DB = new Zend_Db_Adapter_Pdo_Mysql($params);$request = $this->getRequest();
$data = array(‘first_name’ => $request->getParam(‘first_name’),
‘last_name’ => $request->getParam(‘last_name’),
‘user_name’ => $request->getParam(‘user_name’),
‘password’ => md5($request->getParam(‘password’))
);
$DB->update(‘user’, $data,’id = ‘.$request->getParam(‘id’));
Delete Query
$params = array(‘host’ =>’localhost’, ‘username’ =>’root’, ‘password’ =>”, ‘dbname’ =>’zend’ );
$DB = new Zend_Db_Adapter_Pdo_Mysql($params);$request = $this->getRequest();
$DB->delete(‘user’, ‘id = ‘.$request->getParam(‘id’));
Complete controller
Table name : user ( Fields : id, first_name , last_name, user_name , password)
Input textbox names are (first_name , last_name , user_name , password)
public function processAction()
{$params = array(‘host’ => ‘localhost’ , ‘username’ =>’root’ , ‘password’ =>” , ‘dbname’ =>’zend’ );
$DB = new Zend_Db_Adapter_Pdo_Mysql($params);
$request = $this->getRequest(); //create a request object
$data = array(‘first_name’ => $request->getParam(‘first_name’),
‘last_name’ => $request->getParam(‘last_name’),
‘user_name’ => $request->getParam(‘user_name’),
‘password’ => md5($request->getParam(‘password’))
);
$DB->insert(‘user’, $data); // insertion code
$this->view->assign(‘title’,'Registration Process’);
$this->view->assign(‘description’,'Registration succes’);
}

Sunday, June 2, 2013

Differences between Java EE and Java SE

Differences between Java EE and Java SE

Java technology is both a programming language and a platform. The Java programming language is a high-level object-oriented language that has a particular syntax and style. A Java platform is a particular environment in which Java programming language applications run.
There are several Java platforms. Many developers, even long-time Java programming language developers, do not understand how the different platforms relate to each other.

The Java Programming Language Platforms

There are four platforms of the Java programming language:
  • Java Platform, Standard Edition (Java SE)
  • Java Platform, Enterprise Edition (Java EE)
  • Java Platform, Micro Edition (Java ME)
  • JavaFX
All Java platforms consist of a Java Virtual Machine (VM) and an application programming interface (API). The Java Virtual Machine is a program, for a particular hardware and software platform, that runs Java technology applications. An API is a collection of software components that you can use to create other software components or applications. Each Java platform provides a virtual machine and an API, and this allows applications written for that platform to run on any compatible system with all the advantages of the Java programming language: platform-independence, power, stability, ease-of-development, and security.

Java SE

When most people think of the Java programming language, they think of the Java SE API. Java SE's API provides the core functionality of the Java programming language. It defines everything from the basic types and objects of the Java programming language to high-level classes that are used for networking, security, database access, graphical user interface (GUI) development, and XML parsing.
In addition to the core API, the Java SE platform consists of a virtual machine, development tools, deployment technologies, and other class libraries and toolkits commonly used in Java technology applications.

Java EE

The Java EE platform is built on top of the Java SE platform. The Java EE platform provides an API and runtime environment for developing and running large-scale, multi-tiered, scalable, reliable, and secure network applications.

Java ME

The Java ME platform provides an API and a small-footprint virtual machine for running Java programming language applications on small devices, like mobile phones. The API is a subset of the Java SE API, along with special class libraries useful for small device application development. Java ME applications are often clients of Java EE platform services.

JavaFX

JavaFX is a platform for creating rich internet applications using a lightweight user-interface API. JavaFX applications use hardware-accelerated graphics and media engines to take advantage of higher-performance clients and a modern look-and-feel as well as high-level APIs for connecting to networked data sources. JavaFX applications may be clients of Java EE platform services.

Drop-down select from database with ajax and php

Drop-down select from database with ajax and php

 Download

//index.php
<?php
include "connection.php";
$sel_sql="select * from tb_country";
$sel_exe=mysql_query($sel_sql);
?>
<html>
<head>
<script language="javascript">
function showHint(str)
{
var xmlhttp;
if (str.length==0)
{
document.getElementById("statediv").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("statediv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","ajax.php?q="+str,true);
xmlhttp.send(null);
}
</script>
</head>
<body>
<form method="POST" name="frm">
Select Country:-
<select name="country" id="country" onChange="showHint(this.value);">
<option value="0">--Select--</option>
<?php while($sel_rows=mysql_fetch_array($sel_exe))
{
?>
<option value="<?php echo $sel_rows['country_id']; ?>">
<?php echo $sel_rows['country_name']; ?>
</option>
<?php  }   ?>
</select>
<br/>
Select state:
<div id="statediv">
<select name="state" id="state">
<option>--Select State--</option>
<option></option>
</div>
</form>
</body>
</html>
//connection.php
<?php
$mysql_hostname = "localhost";
$mysql_user = "root";
$mysql_password = "ednalan";
$mysql_database = "test";
$bd = mysql_connect($mysql_hostname, $mysql_user, $mysql_password) or die("Could not connect database");
mysql_select_db($mysql_database, $bd) or die("Could not select database");
?>
//ajax.php
<?php
include "connection.php";
$country_name = $_GET["q"];
$sql="SELECT * FROM tb_state WHERE country_id='$country_name'";
$result = mysql_query($sql);
?>
<select name="state" id="state">
<?php
while($row=mysql_fetch_array($result))
{
$id=$row['state_id'];
$state=$row['state_name'];
echo '<option value="'.$id.'">'.$state.'</option>';
}
?>
</select>

Saturday, June 1, 2013

JAVASCRIPT calculate date and date difference

JAVASCRIPT calculate date and date difference


<div id="someid"></div>
<script type="text/javascript">
//day/month/year
t1="02/06/2013";
t2="01/07/2013";
//Total time for one day
 var one_day=1000*60*60*24; 
//Here we need to split the inputed dates to convert them into standard format
var x=t1.split("/");     
var y=t2.split("/");
//date format(Fullyear,month,date) 
var date1=new Date(x[2],(x[1]-1),x[0]);
var date2=new Date(y[2],(y[1]-1),y[0])
var month1=x[1]-1;
var month2=y[1]-1;
//Calculate difference between the two dates, and convert to days
var Diff_result=Math.ceil((date2.getTime()-date1.getTime())/(one_day)); //results 29=Days
var somediv = document.getElementById('someid');
somediv.innerHTML = Diff_result + "=Days";
</script>

5 Tips for optimizing and cleaning up CSS

5 Tips for optimizing and cleaning up CSS 

1. Use shorthand
CSS properties like padding, margin, background, font and border allow usage of shorthand. Combining values using shorthand help in cutting down code and coding time.
For example:
padding-left:0px ;
padding-top:4px;
padding-bottom: 3px;
padding-right:0px;
can be written as:
padding:0 4px 3px 0;
*hint : top – right – bottom – left*
2. Omit units like px / em / % when value is zero
As you may have noticed in the above example, I have eliminated px from the properties that are of value 0. Zero (0) doesn’t require units. 0px is the same as 0em or 0%.
3. Color Prefixes
Typically HEX codes used to define color values are 6 characters long. However, certain color combinations can be reduced and represented in 3 chars.
For example:
color:#000000;
can be written as:
color:#000;
also
color: #aa88aa;
can be written as:
color:#a8a;
4. Group Elements
If there are multiple elements like h1, h2, h3 with common properties, instead of declaring them separately it helps optimize your CSS by combining them, like as follows:
h1, h2, h3{
padding:0 ;
margin:0;
color:#000;
}
5. Use a compressor
Once you are done with your CSS wizardry, it is a good idea to use a CSS compressor tool to shed the excess load off your CSS files. There is a bunch of such services available online, like: cleancss.com, codebeautifier.com, and cssoptimiser.com to name a few. Make sure you attempt optimizing your CSS this way at the end of your project, just before going live because it is likely that you will be served up with a human unreadable (but browser friendly) block of code.

Flash like hover effect using jQuery

Flash like hover effect using jQuery




 
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
 $('.verttabnav ul li a').hover(function() { //mouse in
  $(this).animate({ paddingRight: '+=10px' }, 300);
  $(this).parent().animate({ left:'-=7'}, 300);
 }, function() { //mouse out
  $(this).animate({ paddingRight: '-=10px' }, 100);
    $(this).parent().animate({ left:'+=7'}, 300);
 });
});
</script>
<style type="text/css">
.verttabnav {
 width:300px;
}
.verttabnav ul {
 margin: 0 4px 0 10px;
 list-style:none;
}
.verttabnav ul li {
 padding:0 0 0 0;
 border-bottom:1px solid #A38872;
 border-right:1px solid #A38872;
 border-top:1px solid #A38872;
 border-left:1px solid #A38872;
 margin:-1px 0 2px 0;
 position:relative;
 background:#FFEFD7;
}
.verttabnav ul li a {
 padding:10px 30px 10px 0;
 font-size:11px;
 color:#8c6d53;
 text-decoration:none;
 text-transform:uppercase;
 text-align:right;
 font-weight:bold;
 display:block;
}
.verttabnav ul li a:hover {
 color:#000;
}
</style>
<div class="verttabnav">
  <ul >
    <li><a href="#">Menu Item 1</a></li>
    <li><a href="#">Menu Item 2</a></li>
    <li><a href="#">Menu Item 3</a></li>
    <li><a href="#">Menu Item 4</a></li>
    <li><a href="#">Menu Item 5</a></li>
    <li><a href="#">Menu Item 6</a></li>
    <li><a href="#">Menu Item 7</a></li>
    <li><a href="#">Menu Item 8</a></li>
  </ul>
</div>

Wednesday, May 8, 2013

What is the fastest php framework?






















Benchmarked frameworks:

Related Post