Friday, 29 April 2016

How to validate a form in php using jQuery

<?php

// If the form was submitted, scrub the input (server-side validation)
// see below in the html for the client-side validation using jQuery

$name = '';
$gender = '';
$address = '';
$email = '';
$username = '';
$password = '';
$output = '';

if($_POST) {
  // collect all input and trim to remove leading and trailing whitespaces
  $name = trim($_POST['name']);
  $gender = trim($_POST['gender']);
  $address = trim($_POST['address']);
  $email = trim($_POST['email']);
  $username = trim($_POST['username']);
  $password = trim($_POST['password']);
 
  $errors = array();
 
  // Validate the input
  if (strlen($name) == 0)
    array_push($errors, "Please enter your name");

  if (!(strcmp($gender, "Male") || strcmp($gender, "Female") || strcmp($gender, "Other")))
    array_push($errors, "Please specify your gender");
 
  if (strlen($address) == 0)
    array_push($errors, "Please specify your address");
  
  if (!filter_var($email, FILTER_VALIDATE_EMAIL))
    array_push($errors, "Please specify a valid email address");
  
  if (strlen($username) == 0)
    array_push($errors, "Please enter a valid username");
  
  if (strlen($password) < 5)
    array_push($errors, "Please enter a password. Passwords must contain at least 5 characters.");
  
  // If no errors were found, proceed with storing the user input
  if (count($errors) == 0) {
    array_push($errors, "No errors were found. Thanks!");
  }
 
  //Prepare errors for output
  $output = '';
  foreach($errors as $val) {
    $output .= "<p class='output'>$val</p>";
  }
 
}

?>

<html>
<head>
    <!-- Define some CSS -->
  <style type="text/css">
    .label {width:100px;text-align:right;float:left;padding-right:10px;font-weight:bold;}
    #register-form label.error, .output {color:#FB3A3A;font-weight:bold;}
  </style>
 
  <!-- Load jQuery and the validate plugin -->
  <script src="//code.jquery.com/jquery-1.9.1.js"></script>
  <script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js"></script>
 
  <!-- jQuery Form Validation code -->
  <script>
 
  // When the browser is ready...
  $(function() {
 
    // Setup form validation on the #register-form element
    $("#register-form").validate({
  
        // Specify the validation rules
        rules: {
            name: "required",
            gender: "required",
            address: "required",
            email: {
                required: true,
                email: true
            },
            username: "required",
            password: {
                required: true,
                minlength: 5
            }
        },
      
        // Specify the validation error messages
        messages: {
            name: "Please enter your name",
            gender: "Please specify your gender",
            address: "Please enter your address",
            email: "Please enter a valid email address",
            username: "Please enter a valid username",
            password: {
                required: "Please provide a password",
                minlength: "Your password must be at least 5 characters long"
            }
        },
      
        submitHandler: function(form) {
            form.submit();
        }
    });

  });
 
  </script>
</head>
<body>
  <?php echo $output; ?>
  <!--  The form that will be parsed by jQuery before submit  -->
  <form action="./" method="post" id="register-form" novalidate="novalidate">
 
    <div class="label">Name</div><input type="text" id="name" name="name" value="<? echo $name; ?>" /><br />
    <div class="label">Gender</div><select id="gender" name="gender" />
                                      <option value="Female">Female</option>
                                      <option value="Male">Male</option>
                                      <option value="Other">Other</option>
                                   </select><br />
    <div class="label">Address</div><input type="text" id="address" name="address" value="<? echo $address; ?>" /><br />
    <div class="label">Email</div><input type="text" id="email" name="email" value="<? echo $email; ?>" /><br />
    <div class="label">Username</div><input type="text" id="username" name="username" value="<? echo $username; ?>" /><br />
    <div class="label">Password</div><input type="password" id="password" name="password" /><br />
    <div style="margin-left:140px;"><input type="submit" name="submit" value="Submit" /></div>
  
  </form>
 
</body>
</html>

Login validation using php and mysql

      Everybody should see the login pages in most of websites. You should have doubt about this login form, how they validate username and password. There is nothing, just only 2 steps as follows as for login validation using php.
                      1. You enter username and password already registered which is stored in mysql database.
                      2. After you submit a button to login, it check the database values whether the username and password is correct or not using php and mysql query. The mysql query for select a values from mysql database as like this:
             
             ie, SELECT * FROM table_name WHERE name='username' and password='password' 

If it return values correctly, then you can login. Otherwise it give error message.

Simple login validation using php and mysql: 


                      Lets see how to validate the username and password using php.
                      1. First you create table using mysql query like this:

           CREATE TABLE login(name varchar(30), password varchar(30), PRIMARY KEY(name))

Now the table 'login' is created. The field 'name' is primary key. Because the username must be unique.
                      2. Then insert values into table using  mysql query like this:

           INSERT INTO login VALUES('guru','guru') 

Now the table look like this:

login validation using php

                       3. The php script for login validation as follows as:
login.php:
<html>
<head>
<style type="text/css">
 input{
 border:1px solid olive;
 border-radius:5px;
 }
 h1{
  color:darkgreen;
  font-size:22px;
  text-align:center;
 }
</style>
</head>
<body>
<h1>Login<h1>
<form action='#' method='post'>
<table cellspacing='5' align='center'>
<tr><td>User name:</td><td><input type='text' name='name'/></td></tr>
<tr><td>Password:</td><td><input type='password' name='pwd'/></td></tr>
<tr><td></td><td><input type='submit' name='submit' value='Submit'/></td></tr>
</table>

</form>
<?php
session_start();
if(isset($_POST['submit']))
{
 mysql_connect('localhost','root','') or die(mysql_error());
 mysql_select_db('new') or die(mysql_error());
 $name=$_POST['name'];
 $pwd=$_POST['pwd'];
 if($name!=''&&$pwd!='')
 {
   $query=mysql_query("select * from login where name='".$name."' and password='".$pwd."'") or die(mysql_error());
   $res=mysql_fetch_row($query);
   if($res)
   {
    $_SESSION['name']=$name;
    header('location:welcome.php');
   }
   else
   {
    echo'You entered username or password is incorrect';
   }
 }
 else
 {
  echo'Enter both username and password';
 }
}
?>
</body>
</html>


        Where,
                if(isset($_POST['submit']){}    means run after submit a results.
                if($name!=''&&$pwd!=''){}   means if either username or password is empty, it give message like as 'Enter both username and password'.
                mysql_query("select * from login where name='".$name."' and password='".$pwd."'  ")      select the values if the username and password is present.
                $res=mysql_fetch_row($query) return row as numeric array.
You don't know about mysql_fetch_row, then visit mysql-fetch-row in mysql.
               if($res){} validate the result. If it is correct, then your name is stored in session variable and also you'll navigate to 'welcome.php' page. Otherwise you'll get 'You entered username or password is incorrect' message. You want to visit Session in php.
              When you run the above file, it should be like this:
login form in html and php
             
               The php script for welcome page:

 welcome.php:


<?php    
         session_start();
         $name=$_SESSION['name'];    
         echo'welcome :'. $name.'<br>';
         echo'<a href="signout.php">Signout</a>';
?>

      
             Now you enter username and password  'guru' and 'guru', you will navigate to 'welcome.php' page and get output like this:

                   welcome: guru
                   Signout

 If it is wrong, then you can't login.


Signout in php:              


            When you click the signout.php, it destroy the session and return back to login page. The php script for signout page:
signout.php:
<?php    
         session_start();
         session_destroy();
         header('location:login.php');
?>

                session_destroy is used to destroy the session variable in php.

QR Code

 <?php

    
include('../lib/full/qrlib.php');
    include(
'config.php');

    
// how to build raw content - QRCode with Business Card (VCard) + photo
    
    
$tempDir EXAMPLE_TMP_SERVERPATH;
    
    
// here our data
    
$name 'John Doe';
    
$phone '(049)012-345-678';
    
    
// WARNING! here jpeg file is only 40x40, grayscale, 50% quality!
    // with bigger images it will simply be TOO MUCH DATA for QR Code to handle!
    
    
$avatarJpegFileName 'avatar.jpg';
    
    
// we building raw data
    
$codeContents  'BEGIN:VCARD'."\n";
    
$codeContents .= 'FN:'.$name."\n";
    
$codeContents .= 'TEL;WORK;VOICE:'.$phone."\n";
    
$codeContents .= 'PHOTO;JPEG;ENCODING=BASE64:'.base64_encode(file_get_contents($avatarJpegFileName))."\n";
    
$codeContents .= 'END:VCARD';
    
    
// generating
    
QRcode::png($codeContents$tempDir.'027.png'QR_ECLEVEL_L3);
   
    
// displaying
    
echo '<img src="'.EXAMPLE_TMP_URLRELPATH.'027.png" />';

OOP's

Object Oriented Concepts

Before we go in detail, lets define important terms related to Object Oriented Programming.
  • Class − This is a programmer-defined data type, which includes local functions as well as local data. You can think of a class as a template for making many instances of the same kind (or class) of object.
  • Object − An individual instance of the data structure defined by a class. You define a class once and then make many objects that belong to it. Objects are also known as instance.
  • Member Variable − These are the variables defined inside a class. This data will be invisible to the outside of the class and can be accessed via member functions. These variables are called attribute of the object once an object is created.
  • Member function − These are the function defined inside a class and are used to access object data.
  • Inheritance − When a class is defined by inheriting existing function of a parent class then it is called inheritance. Here child class will inherit all or few member functions and variables of a parent class.
  • Parent class − A class that is inherited from by another class. This is also called a base class or super class.
  • Child Class − A class that inherits from another class. This is also called a subclass or derived class.
  • Polymorphism − This is an object oriented concept where same function can be used for different purposes. For example function name will remain same but it make take different number of arguments and can do different task.
  • Overloading − a type of polymorphism in which some or all of operators have different implementations depending on the types of their arguments. Similarly functions can also be overloaded with different implementation.
  • Data Abstraction − Any representation of data in which the implementation details are hidden (abstracted).
  • Encapsulation − refers to a concept where we encapsulate all the data and member functions together to form an object.
  • Constructor − refers to a special type of function which will be called automatically whenever there is an object formation from a class.
  • Destructor − refers to a special type of function which will be called automatically whenever an object is deleted or goes out of scope.

Thursday, 28 April 2016

To Find The Factorial Of A Number Using PHP- Jayesh Ladva

 A factorial of a number n is the product of all the numbers between n and 1.
The easiest way to calculate it is with a for( )
loop which one that starts at n and counts down to 1. Each time the loop runs,
the previously calculated product is multiplied by
the current value of the loop counter and the result is the factorial of the number n.


<?php
$num = 4;
$factorial = 1;
for ($x=$num; $x>=1; $x--) {
  $factorial = $factorial * $x;
  echo $x."</br>";
}
echo "Factorial of $num is $factorial";

?>

Output will be :
4
3
2
1
Factorial of 4 is 24

To find the factorial of a number using form in php
index.php
<?php
/* Function to get Factorial of a Number */
function getFactorial($num)
{
    $fact = 1;
    for($i = 1; $i <= $num ;$i++)
        $fact = $fact * $i;
    return $fact;
}

?>
<!doctype html>
<html>
<head>
<title>Factorial Program using PHP</title>
</head>
<body>
<form action = "" method="post">
Enter the number whose factorial requires <Br />
<input type="number" name="number" id="number" maxlength="4" autofocus required/>
<input type="submit" name="submit" value="Submit" />
</form>
<?php
if(isset($_POST['submit']) and $_POST['submit'] == "Submit")
{
    if(isset($_POST['number']) and is_numeric($_POST['number']))
    {
        echo 'Factorial Of Number: <strong>'.getFactorial($_POST['number']).'</strong>';
    }
}

?>
</body>
</html>

php program for fibonacci series

<?php

//variable initialization
$count = 0 ;
$f1 = 0;
$f2 = 1;

echo $f1." , ";
echo $f2." , ";

  while ($count < 20 ) { 


    $f3 = $f2 + $f1 ;
    echo $f3." , ";
    $f1 = $f2 ;
    $f2 = $f3 ;
    $count = $count + 1;


  } 


?>

Write a function to check a number is prime or not.

<?php
function IsPrime($n)
{
  for($x=2; $x<$n; $x++)
  {
    if($n %$x ==0)
    {
      return 0;
    }
  }
  return 1;
}
$a = IsPrime(3);

if ($a==0)
echo 'This is not a Prime Number.....';
else
echo 'This is  a Prime Number..';
?>  


Fro any query or result you want just leave comment will get back to you

How to find the list prime number from given number?

function prima($n){

  for($i=1;$i<=$n;$i++){  //numbers to be checked as prime

          $counter = 0; 
          for($j=1;$j<=$i;$j++){ //all divisible factors


                if($i % $j==0){ 

                      $counter++;
                }
          }

        //prime requires 2 rules ( divisible by 1 and divisible by itself)
        if($counter==2){

               print $i." is Prime <br/>";
        }
    }
} 

prima(20);
 
OUTPUT 
 2 is Prime 
 3 is Prime 
 5 is Prime 
 7 is Prime 
 11 is Prime 
 13 is Prime 
 17 is Prime 
 19 is Prime 

What is INDEXING and its Advantage & Disadvantage


Indexing

It is a data structure that improves the speed of search in database. We add the indexing on columns of table. We can one or more indexing on table.

Advantage of Indexing
It improve the speed of search. If we add indexing on any column, It will search faster.

Disadvantage of Indexing

INSERT and UPDATE statements take little more time on tables.


Column Index: In this type, we add indexing on single column

   
ALTER TABLE table_name ADD INDEX (field_name);
 

Concatenated Index: In this type, we add indexing on two OR more columns. 

ALTER TABLE table_name ADD INDEX (field_name1, field_name2);

Add Indexing
alter table `cities` add index name (name)

List all the Indexing in cities table
show index from `cities`

Drop Indexing 
alter table `cities` drop index name