Friday, 11 September 2015

PHP BASIC + ADVANCE PHP WITH AJAX & MYSQL TUTORIALS WITH PROGRAM EXAMPLES

05:07

What is PHP ?
  • PHP is an acronym for "PHP: Hypertext Preprocessor"
  • PHP is a widely-used, open source scripting language
  • PHP scripts are executed on the server
  • PHP is free to download and use

What is a PHP File   ?
  • PHP files can contain text, HTML, CSS, JavaScript, and PHP code
  • PHP code are executed on the server, and the result is returned to the browser as plain HTML
  • PHP files have extension ".php"

What Can PHP Do   ?
  • PHP can generate dynamic page content
  • PHP can create, open, read, write, delete, and close files on the server
  • PHP can collect form data
  • PHP can send and receive cookies
  • PHP can add, delete, modify data in your database
  • PHP can be used to control user-access
  • PHP can encrypt data.

Why PHP ?
  • PHP runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.)
  • PHP is compatible with almost all servers used today (Apache, IIS, etc.)
  • PHP supports a wide range of databases.
  • PHP is free. Download it from the official PHP resource: www.php.net
  • PHP is easy to learn and runs efficiently on the server side.

Basic PHP Syntax:
A PHP script can be placed anywhere in the document.
A PHP script starts with <?php and ends with ?>:
<?php
// PHP code goes here
?>
Creating (Declaring) PHP Variables:
In PHP, a variable starts with the $ sign, followed by the name of the variable:
Example:
<?php

$txt = "Hello world!";
$x = 5;
$y = 10.5;
?>
Output:
Hello world!
5
10.5

PHP echo and print Statements :

echo and print are more or less the same. They are both used to output data to the screen.
The differences are small: echo has no return value while print has a return value of 1 so it can be used in expressions. echo can take multiple parameters (although such usage is rare) while print can take one argument. echo is marginally faster than print.
Echo example:
<?php
$txt1 = "Learn PHP";
$txt2 = "vissicomp.com";
$x = 5;
$y = 4;

echo "<h2>$txt1</h2>";
echo "Study PHP at $txt2<br>";
echo $x + $y;
?>
Output:
Learn PHP
Study PHP at vissicomp.com
9

Print Example:

<?php
print "<h2>PHP is Fun!</h2>";
print "Hello world!<br>";
print "I'm about to learn PHP!";
?> 

PHP Data Types :
Variables can store data of different types, and different data types can do different things.
PHP supports the following data types:
  • String
  • Integer
  • Float (floating point numbers - also called double)
  • Boolean
  • Array
  • Object
  • NULL
  • Resource
  •  
PHP  String :
·         A string is a sequence of characters, like "Hello world!".
·         A string can be any text inside quotes. You can use single or double quotes:

<?php 
$x = "Hello world!";
$y = 'Hello world!';

echo $x;
echo "<br>";
 
echo $y;
?>

Output:

Hello world!
Hello world!

PHP Integer :
An integer is a whole number (without decimals).  It is a number between -2,147,483,648 and +2,147,483,647.
Rules for integers:
  • An integer must have at least one digit (0-9)
  • An integer cannot contain comma or blanks
  • An integer must not have a decimal point
  • An integer can be either positive or negative
  • Integers can be specified in three formats: decimal (10-based), hexadecimal (16-based - prefixed with 0x) or octal (8-based - prefixed with 0)
In the following example $x is an integer. The PHP var_dump() function returns the data type and value:

<?php 

$x = 5985;
var_dump($x);

?>

Output:
int(5985)

PHP Float  :
A float (floating point number) is a number with a decimal point or a number in exponential form.
In the following example $x is a float. The PHP var_dump() function returns the data type and value:
<?php 
$x = 10.365;
var_dump($x);
?>
Output:
float(10.365)

PHP Array   :
An array stores multiple values in one single variable.
In the following example $cars is an array. The PHP var_dump() function returns the data type and value:

<?php 

$cars = array("Volvo","BMW","Toyota");
var_dump($cars);

?>
Output:
array(3) { [0]=> string(5) "Volvo" [1]=> string(3) "BMW" [2]=> string(6) "Toyota" }

PHP Object :
An object is a data type which stores data and information on how to process that data.
In PHP, an object must be explicitly declared.
First we must declare a class of object. For this, we use the class keyword. A class is a structure that can contain properties and methods:
<?php
class Car {

    function Car()
{

        $this->model = "VW";
    }
}

// create an object

$herbie = new Car();

// show object properties

echo $herbie->model;

?>

Output :
VW

PHP NULL Value  :

Null is a special data type which can have only one value: NULL.
A variable of data type NULL is a variable that has no value assigned to it.
Tip: If a variable is created without a value, it is automatically assigned a value of NULL.
Variables can also be emptied by setting the value to NULL:

Example :
<?php

$x = "Hello world!";

$x = null;

var_dump($x);

?>

Output:

NULL


PHP String Functions :

Get The Length of a String:
The PHP strlen() function returns the length of a string (number of characters).
The example below returns the length of the string "Hello world!":
<?php
echo strlen("Hello world!"); // outputs 12
?>

Output:
12


Count The Number of Words in a String
The PHP str_word_count() function counts the number of words in a string:
<?php

echo str_word_count("Hello world!"); // outputs 2

?>
Output :
2

Reverse a String
The PHP strrev() function reverses a string:
<?php

echo strrev("Hello world!");   // outputs !dlrow olleH

?>
Output:
!dlrow olleH

Search For a Specific Text Within a String
The PHP strpos() function searches for a specific text within a string.
If a match is found, the function returns the character position of the first match. If no match is found, it will return FALSE.
The example below searches for the text "world" in the string "Hello world!":
<?php

echo strpos("Hello world!", "world"); // outputs 6

?>
Output:
6

Replace Text Within a String
The PHP str_replace() function replaces some characters with some other characters in a string.
The example below replaces the text "world" with "Dolly":
<?php

echo str_replace("world", "Dolly", "Hello world!"); // outputs Hello Dolly!

?>

Hello Dolly!






Create a PHP Constant

To create a constant, use the define() function.

Syntax

define(name, value, case-insensitive)
Parameters:
  • name: Specifies the name of the constant
  • value: Specifies the value of the constant
  • case-insensitive: Specifies whether the constant name should be case-insensitive. Default is false
The example below creates a constant with a case-sensitive name:
<?php

define("GREETING", "Welcome to vissicomp.com!");

echo GREETING;

?>

Output:
Welcome to vissicomp.com!


PHP Operators
Operators are used to perform operations on variables and values.
PHP divides the operators in the following groups:
  • Arithmetic operators
  • Assignment operators
  • Comparison operators
  • Increment/Decrement operators
  • Logical operators
  • String operators
  • Array operators

PHP Arithmetic Operators:

+
Addition

 

<?php

$x = 10; 
$y = 6;

echo $x + $y;
?>
 
Output:
16

-
Subtraction
<?php
$x = 10; 
$y = 6;

echo $x - $y;
?>
  
Output:
4
*
Multiplication

<?php
$x = 10; 
$y = 6;

echo $x * $y;
?>
  
Output:
60
/
Division

<?php
$x = 10; 
$y = 6;

echo $x / $y;

?>
  
Output:
%
Modulus

<?php
$x = 10; 
$y = 6;

echo $x % $y;
?>
 
Output:
4

PHP Assignment  Operators :

The PHP assignment operators are used with numeric values to write a value to a variable.
x = y
<?php
$x = 10; 
echo $x;
?>
 
Output:
10

x += y
x = x + y
Addition

<?php

$x = 20; 
$x += 100;

echo $x;
?>
 
Output:
120

x -= y
x = x - y
Subtraction


<?php

$x = 50;
$x -= 30;

echo $x;

?>
 
Output:
20
x *= y
x = x * y
Multiplication

<?php

$x = 10; 

$y = 6;

echo $x * $y;

?>
 
Output:
60

x /= y
x = x / y
Division

<?php

$x = 10;
$x /= 5;

echo $x;

?>
 
Output:
2
x %= y
x = x % y
Modulus
<?php
$x = 15;
$x %= 4;

echo $x;
?>
 
Output:
3

PHP Comparison Operators

The PHP comparison operators are used to compare two values (number or string):
==
Equal
$x == $y
Returns true if $x is equal to $y

<?php
$x = 100; 
$y = "100";

var_dump($x == $y); // returns true because values are equal

?>
 
Output:
Bool(true)

!=
Not equal
$x != $y
Returns true if $x is not equal to $y


<?php
$x = 100; 
$y = "100";

var_dump($x != $y); // returns false because values are equal
?>
 
Output:
Bool(false)

> 
Greater than
$x > $y
Returns true if $x is greater than $y
<?php
$x = 100;
$y = 50;

var_dump($x > $y); // returns true because $x is greater than $y
?>
  

Output:
bool(true)

< 
Less than
$x < $y
Returns true if $x is less than $y
<?php
$x = 10;
$y = 50;

var_dump($x <  $y); // returns true because $x is less than $y
?>
  
Output:
Bool(true)

>=
Greater than or equal to
$x >= $y
Returns true if $x is greater than or equal to $y

<?php

$x = 50;

$y = 50;

var_dump($x >= $y); // returns true because $x is greater than or equal to $y

?>
 
Output:
bool(true)


<=
Less than or equal to
$x <= $y
Returns true if $x is less than or equal to $y

<?php
$x = 50;
$y = 50;

var_dump($x <= $y); // returns true because $x is less than or equal to $y
?>
  
Output:
bool(true)


PHP Increment / Decrement Operators:

The PHP increment operators are used to increment a variable's value.
The PHP decrement operators are used to decrement a variable's value.
++$x
Pre-increment
Increments $x by one, then returns $x
<?php
$x = 10; 
echo ++$x;
?>
Output:
11

$x++
Post-increment
Returns $x, then increments $x by one

<?php
$x = 10; 
echo $x++;
?>
  
Output:
10
--$x
Pre-decrement
Decrements $x by one, then returns $x
<?php
$x = 10; 
echo --$x;
?>
   
Output:
9
$x--
Post-decrement
Returns $x, then decrements $x by one

<?php
$x = 10; 
echo $x--;
?>
 
Output:
10

PHP Logical Operators:

The PHP logical operators are used to combine conditional statements.


&&
And
$x && $y
True if both $x and $y are true

<?php
$x = 100; 
$y = 50;

if ($x == 100 && $y == 50) {
     echo "Hello world!";
}
?>
 
Output:
Hello world!

||
Or
$x || $y
True if either $x or $y is true
<?php

$x = 100; 
$y = 50;

if ($x == 100 || $y == 80) {
     echo "Hello world!";
}
?>
   
Output:

Hello world!

!
Not
!$x
True if $x is not true

<?php

$x = 100; 

if ($x !== 90)
{
     echo "Hello world!";
}

?>
 
Output:
Hello world!


Array-in-PHP  :

What is an Array?
An array is a special variable, which can hold more than one value at a time.
If you have a list of items (a list of car names, for example), storing the cars in single variables    could    look   like   this:

$cars1 = "Volvo";
$cars2 = "BMW";
$cars3 = "Toyota";

However, what if you want to loop through the cars and find a specific one? And what if you had not 3 cars, but 300?
The solution is to create an array!
An array can hold many values under a single name, and you can access the values by referring to an index number.

Create an Array in PHP :
In PHP, the array() function is used to create an array:
array();


In PHP, there are three types of arrays:
Indexed arrays - Arrays with a numeric index.
Associative arrays - Arrays with named keys.
Multidimensional arrays - Arrays containing one or more arrays.

(1)PHP Indexed Arrays :
There are two ways to create indexed arrays:
The index can be assigned automatically (index always starts at 0), like this:
$cars = array("Volvo", "BMW", "Toyota");

or the index can be assigned manually:
$cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota";


Example:
<!DOCTYPE html>
<html>
<body>

<?php
$cars = array("Volvo", "BMW", "Toyota"); 
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>

</body>
</html>

(2)PHP Associative Arrays:
Associative arrays are arrays that use named keys that you assign to them.
There are two ways to create an associative array: 
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");

or:
$age['Peter'] = "35";
$age['Ben'] = "37";
$age['Joe'] = "43";



<!DOCTYPE html>
<html>
<body>

<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
echo "Peter is " . $age['Peter'] . " years old.";
?>

</body>
</html>

(3)Multidimensional Associative Array:
<?php
$marks=array(
"mohammad"=>array
(
"physics"=> 35,
"maths"=> 30,
"chemistry"=>39
),

"zara"=>array

(
"physics"=> 35,
"maths"=> 40,
"chemistry"=> 21
),
"quara"=>array
(
"physics"=> 45,
"maths"=> 48,
"chemistry"=> 45
)
);

echo "value of mohammad array".'<br>';

echo $marks["mohammad"]["physics"].'<br>';
echo $marks["mohammad"]["maths"].'<br>';
echo $marks["mohammad"]["chemistry"].'<br>';
echo" value of zara array".'<br>';
echo $marks ["zara"]["physics"].'<br>';
echo $marks["zara"]["maths"].'<br>';
echo $marks["zara"]["chemistry"].'<br>';
echo"value of quara array".'<br>';
echo $marks["quara"]["physics"].'<br>';
echo $marks["quara"]["maths"].'<br>';
echo $marks["quara"]["chemistry"].'<br>';
?>


OUTPUT :
value of mohammad array
35
30
39
value of zara array
35
40
21
value of quara array
45
48
45

(4)Multidimensional   Index   Array :
<?php
$abc=array
(
array(1,2,3),
array(4,5,6),
array(6,7,8)
);
echo"value of position 0,0=".$abc[0][0].'<br>';
echo "value of position 0,1=".$abc[0][1].'<br>';
echo "value of position 0,2=".$abc[0][2].'<br>';
echo "value of position 1,0=".$abc[1][0].'<br>';
echo "value of position 1,1=".$abc[1][1].'<br>';
echo "value of position 1,2=".$abc[1][2].'<br>';
echo "value of position 2,0=".$abc[2][0].'<br>';
echo "value of position 2,1=".$abc[2][1].'<br>';
echo "value of position 2,2=".$abc[2][2];

?>


OUTPUT :

value of position 0,0=1
value of position 0,1=2
value of position 0,2=3
value of position 1,0=4
value of position 1,1=5
value of position 1,2=6
value of position 2,0=6
value of position 2,1=7
value of position 2,2=8





Array Function :

  • sort() - sort arrays in ascending order.
  • rsort() - sort arrays in descending order.
  • asort() - sort associative arrays in ascending order, according to the value.

(1)asort()  example:

<?php

$number=array(1, 2, 5 ,6, 7);
asort($number);

foreach($number as $x=>$x_value)
    {
    echo "Key=" . $x . ", Value=" . $x_value;
    echo "<br>";
    }
?>

Output:
Key=0, Value=1
Key=1, Value=2
Key=2, Value=5
Key=3, Value=6
Key=4, Value=7

(2)rsort() example:

<?php

$number=array(1,2,5,6,7);

rsort($number);

$clength=count($number);

for($x=0;$x<$clength;$x++)
   {
   echo $number[$x];
   echo "<br>";
   }
?>

Output:
7
6
5
2
1






PHP Conditional Statements

Very often when you write code, you want to perform different actions for different decisions. You can use conditional statements in your code to do this.
In PHP we have the following conditional statements:
  • if statement - executes some code only if a specified condition is true
  • if...else statement - executes some code if a condition is true and another code if the condition is false
  • if...elseif....else statement - specifies a new condition to test, if the first condition is false
  • switch statement - selects one of many blocks of code to be executed

PHP - The if Statement

The  if statement is used to execute some code only if a specified condition is true.

Syntax

if (condition) {
    code to be executed if condition is true
;
}

Example


<?php


$color="red";


If($color=="red")
{

echo "color is red";

}

?>

OUTPUT:
color is red

PHP - The if...else Statement

Use the if....else statement to execute some code if a condition is true and another code if the condition is false.

Syntax

if (condition) {
    code to be executed if condition is true;
} else {
    code to be executed if condition is false;
}

<?php


$color="red";


if($color=="red")
{

echo "color is red";

}

else


{

echo  "not red color";


}


?>
OUTPUT:
color is red

PHP - The if...else if....else Statement

Use the if....else if...else statement to specify a new condition to test, if the first condition is false.

Syntax

if (condition) {
    code to be executed if condition is true;
} elseif (condition) {
    code to be executed if condition is true;
} else {
    code to be executed if condition is false;
}


<?php

$color="orange";


if($color=="red")
{

echo "color is red";

}

else if($color=="orange")

{



echo "color is orange";

}

else

{

echo "No color:";


}
?>

Output:
Color is orange



The PHP switch Statement

Use the switch statement to select one of many blocks of code to be executed.

Syntax

switch (n) {
    case label1:
        code to be executed if n=label1;
        break;
    case label2:
        code to be executed if n=label2;
        break;
    case label3:
        code to be executed if n=label3;
        break;
    ...
    default:
        code to be executed if n is different from all labels;
}
This is how it works: First we have a single expression n (most often a variable), that is evaluated once. The value of the expression is then compared with the values for each case in the structure. If there is a match, the block of code associated with that case is executed. Use break to prevent the code from running into the next case automatically. The default statement is used if no match is found.

Example

<?php

$color="blue";

switch($color)

{

case "red":
echo "color is red";

break;

case  "blue":


echo "color is blue";

break;

case "orange":

echo "color is orange";

break;

default:

echo "no color";

break;
}
?>
Output:
color is blue





Preparing   a simple Application for Calculator using Switch:

(1)save following code  “form.html”:
<form action="switch.php" method="post">
a <input type="text" name=a>
b <input type="text" name=b>

select for calculation
<select name="cal">
<option value=1> addition </option>
<option value=2> subtraction </option>
<option value=3> multiplcation </option>
<option value=4> division </option>
</select>
<input type="submit" name="submit" value="calculation">
</form>

(2)write code for switch.php :
<?php
$cal=$_POST['cal'];
$a=$_POST['a'];
$b=$_POST['b'];

switch ($cal)
{
case 1:
$c=$a+$b;
echo "add=".$c;
break;
case 2:
$c=$a-$b;
echo "sub=".$c;
break;
case 3:
$c=$a*$b;
echo "mul=".$c;
break;
case 4:
$c=$a/$b;
echo "div=".$c;
break;
default:
echo "no cal";
break;
}
?>

now run application:
"Localhost/yourfoldername/form.html"
output:
and after click on calculation button output will be :
add=4


PHP Loops

Often when you write code, you want the same block of code to run over and over again in a row. Instead of adding several almost equal code-lines in a script, we can use loops to perform a task like this.
In PHP, we have the following looping statements:
  • while - loops through a block of code as long as the specified condition is true
  • do...while - loops through a block of code once, and then repeats the loop as long as the specified condition is true
  • for - loops through a block of code a specified number of times
  • foreach - loops through a block of code for each element in an array


The PHP for Loop

The for loop is used when you know in advance how many times the script should run.

Syntax

for (init counter; test counter; increment counter) {
    code to be executed;
}
Parameters:
  • init counter: Initialize the loop counter value
  • test counter: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues. If it evaluates to FALSE, the loop ends.
  • increment counter: Increases the loop counter value

Example:

<?php

for($i=0; $i<5;$i++)

{


echo $i;
echo ‘<br>’;


}


?>
Output:
0
1
2
3
4

The  PHP   foreach   Loop

The foreach loop works only on arrays, and is used to loop through each key/value pair in an array.

Syntax

foreach ($array as $value) {
    code to be executed;
}
For every loop iteration, the value of the current array element is assigned to $value and the array pointer is moved by one, until it reaches the last array element.
The following example demonstrates a loop that will output the values of the given array ($colors):

Example

<?php 
$colors = array("red", "green", "blue", "yellow"); 

foreach ($colors as $value) {
    echo "$value <br>";
}
?>
Output:
red 
green 
blue 
yellow 


The PHP while Loop

The while   loop  executes a block of code as long as the specified condition is true.

Syntax

while (condition is true) {
    code to be executed;
}

Example:


<?php
$i=0;
while($i<5)
{
echo $i;
echo ‘<br>’;
$i++;
}
?>
Output:
0
1
2
3
4


 The PHP do...while Loop

The do...while loop will always execute the block of code once, it will then check the condition, and repeat the loop while the specified condition is true.
Syntax
do {
    code to be executed;
} while (condition is true);

Example:

<?php
$i=0;
do
{

echo $i;

$i++;

}

while($i<5);

?>

Output:
0
1
2
3
4

PHP 5 Functions

The real power of PHP comes from its functions; it has more than 1000 built-in functions.

PHP User Defined Functions

Besides the built-in PHP functions, we can create our own functions.
A function is a block of statements that can be used repeatedly in a program.
A function will not execute immediately when a page loads.
A function will be executed by a call to the function.

Create a User Defined Function in PHP

A user defined function declaration starts with the word "function":

Syntax

function functionName() {
    code to be executed;
}

In the example below, we create a function named "writeMsg()". The opening curly brace ( { ) indicates the beginning of the function code and the closing curly brace ( } ) indicates the end of the function. The function outputs "Hello world!". To call the function, just write its name:

Example


<?php

function writeMsg()
 {
    echo "Hello
 world!";
}

writeMsg(); // call the function

?>

Output:
Hello world!

PHP Function Arguments:

Information can be passed to functions through arguments. An argument is just like a variable.
Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just seperate them with a comma.
The following example has a function with one argument ($fname). When the familyName() function is called, we also pass along a name (e.g. Jani), and the name is used inside the function, which outputs several different first names, but an equal last name:

Example


<?php
function familyName($fname) {
    echo "$fname Refsnes.<br>";
}

familyName("Jani");
familyName("Hege");
familyName("Stale");
familyName("Kai Jim");
familyName("Borge");
?>
Output:
Jani Refsnes.
Hege Refsnes.
Stale Refsnes.
Kai Jim Refsnes.
Borge Refsnes.

The following example has a function with two arguments ($fname and $year):

Example


<?php
function familyName($fname, $year) {
    echo "$fname Refsnes. Born in $year <br>";
}

familyName("Hege", "1975");

familyName("Stale", "1978");

familyName("Kai Jim", "1983");

?>
Output:
Hege Refsnes. Born in 1975 
Stale Refsnes. Born in 1978 
Kai Jim Refsnes. Born in 1983 

PHP Functions - Returning values

To let a function return a value, use the return statement: 

Example

<?php
function sum($x, $y) {
    $z = $x + $y;
    return $z;
}

echo "5 + 10 = " . sum(5, 10) . "<br>";
echo "7 + 13 = " . sum(7, 13) . "<br>";
echo "2 + 4 = " . sum(2, 4);
?>

Output:
5 + 10 = 15
7 + 13 = 20
2 + 4 = 6


PHP  FORM  HANDLING :

The PHP superglobals $_GET and $_POST are used to collect form-data.
PHP - A Simple HTML Form

The example below displays a simple HTML form with two input fields and a submit button:

Example

<html>
<body>

<form action="welcome.php" method="post">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>

</body>
</html>

When the user fills out the form above and clicks the submit button, the form data is sent for processing to a PHP file named "welcome.php". The form data is sent with the HTTP POST method.
To display the submitted data you could simply echo all the variables. The "welcome.php" looks like this:
<html>
<body>

Welcome <?php echo $_POST["name"]; ?><br>
Your email address is: <?php echo $_POST["email"]; ?>

</body>
</html>
The output could be something like this:
Welcome John
Your email address is john.doe@example.com
The same result could also be achieved using the HTTP GET method:
Example

<html>
<body>

<form action="welcome_get.php" method="get">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>

</body>
</html>
and "welcome_get.php" looks like this:
<html>
<body>

Welcome <?php echo $_GET["name"]; ?><br>
Your email address is: <?php echo $_GET["email"]; ?>

</body>
</html>
The code above is quite simple. However, the most important thing is missing. You need to validate form data to protect your script from malicious code.
Think SECURITY when processing PHP forms!

This page does not contain any form validation, it just shows how you can send and retrieve form data.
However, the next pages will show how to process PHP forms with security in mind! Proper validation of form data is important to protect your form from hackers and spammers!
GET vs. POST

Both GET and POST create an array (e.g. array( key => value, key2 => value2, key3 => value3, ...)). This array holds key/value pairs, where keys are the names of the form controls and values are the input data from the user.
Both GET and POST are treated as $_GET and $_POST. These are superglobals, which means that they are always accessible, regardless of scope - and you can access them from any function, class or file without having to do anything special.
$_GET is an array of variables passed to the current script via the URL parameters.
$_POST is an array of variables passed to the current script via the HTTP POST method.
When to use GET?

Information sent from a form with the GET method is visible to everyone (all variable names and values are displayed in the URL). GET also has limits on the amount of information to send. The limitation is about 2000 characters. However, because the variables are displayed in the URL, it is possible to bookmark the page. This can be useful in some cases.
GET may be used for sending non-sensitive data.
Note: GET should NEVER be used for sending passwords or other sensitive information!
When to use POST?

Information sent from a form with the POST method is invisible to others (all names/values are embedded within the body of the HTTP request) and has no limits on the amount of information to send.
Moreover POST supports advanced functionality such as support for multi-part binary input while uploading files to server.
However, because the variables are not displayed in the URL, it is not possible to bookmark the page.



 PHP  FORM  VALIDATION  USING JAVASCRIPT  :


<html>
<head>
<title>
Simple Client Side Validation
</title>
<script  type="text/javascript">

function  valid()
{

if(myform.name.value=="")
{

alert("enter your name");

return false;

document.myform.name.focus();
}


if(myform.contact.value=="")
{
alert("enter your contact");
return false;
document.myform.contact.focus();
}
if(isNaN(myform.contact.value))
{

alert("enter numeric value in contact");
return false;
document.myform.contact.focus();
}

if(myform.city.value=="")
{

alert("enter your city");

return false;

document.myform.city.focus();

}

if(myform.email.value=="")
{

alert("enter your email");

document.myform.email.focus();

return false;

}

if(myform.address.value=="")
{

alert("enter your address"); 

document.myform.address.focus();

return false;

}

}

</script>

</head>
<body>
<form name="myform"  action="submit.php" method="post"  onsubmit="return(valid());" >
Name <input type="text" name="name"  >
contact<input type="text" name="contact">
city<input type=text   name="city">
email<input type=text name="email">
Address<textarea  rows=5  cols=5  name=address> </textarea>
<input   type=submit     name=submit>
</form>
</body>
</html>


FORM  VALIDATION  USING    PHP :

(1)first    write   code  for   "form.html"    file.

<form     action="validation.php"      method="post">

Name     <input type="text"         name="name">

Contact    <input type="text"          name="contact">

Email    <input type="text"             name="email">

<input type="submit"    name="submit"     value="submit"  >

</form>
(2)WRITE CODE FOR  “validation.php”  file:
<?php


$msg=array();






if(empty($_POST['email']))


{


$msg="enter your email";

}


$regex = "^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$^";


if(!preg_match( $regex, $_POST['email'] ))


{

$msg="enter your valid email";



}




if(empty($_POST['contact']))

{



$msg="enter your contact";



}

if(strlen($_POST['contact'])>10)

{


$msg="accept only 10 digit";


}



if(!is_numeric($_POST['contact']))

{


$msg="accept only numbers only";


}



if(empty($_POST['name']))

{


$msg="enter your name";



}



if(empty($msg))

{


echo "successful";

}

else

{

echo $msg;


}


?>

From   Validation   to   Prevent   SQL   Injection   Attack  :
<html>
  <head>
      <style>
         .error {color: #FF0000;}
      </style>
   </head>
  
   <body>
      <?php
         // define variables and set to empty values
         $nameErr = $emailErr = $genderErr = $websiteErr = "";
         $name = $email = $gender = $class = $course = $subject = "";
        
         if ($_SERVER["REQUEST_METHOD"] == "POST") {
            if (empty($_POST["name"])) {
               $nameErr = "Name is required";
            }
            else
            {
               $name = test_input($_POST["name"]);
            }
           
            if (empty($_POST["email"])) {
               $emailErr = "Email is required";
            }
            else
            {
               $email = test_input($_POST["email"]);
              
               // check if e-mail address is well-formed
               if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
                  $emailErr = "Invalid email format";
               }
            }
           
            if (empty($_POST["course"])) {
               $course = "";
            }
            else
            {
               $course = test_input($_POST["course"]);
            }
           
            if (empty($_POST["class"])) {
               $class = "";
            }
            else
            {
               $class = test_input($_POST["class"]);
            }
           
            if (empty($_POST["gender"])) {
               $genderErr = "Gender is required";
            }
            else
            {
               $gender = test_input($_POST["gender"]);
            }
           
            if (empty($_POST["subject"])) {
               $subjectErr = "You must select 1 or more";
            }
            else
            {
               $subject = $_POST["subject"];   
            }
         }
        
         function test_input($data) {
            $data = trim($data);
            $data = stripslashes($data);
            $data = htmlspecialchars($data);
            return $data;
         }
      ?>
                               
      <h2>Absolute classes registration</h2>
     
      <p><span class="error">* required field.</span></p>
     
      <form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
         <table>
            <tr>
               <td>Name:</td>
               <td><input type="text" name="name">
                  <span class="error">* <?php echo $nameErr;?></span>
               </td>
            </tr>
           
            <tr>
               <td>E-mail: </td>
               <td><input type="text" name="email">
                  <span class="error">* <?php echo $emailErr;?></span>
               </td>
            </tr>
           
            <tr>
               <td>Time:</td>
               <td> <input type="text" name="course">
                  <span class="error"><?php echo $websiteErr;?></span>
               </td>
            </tr>
           
            <tr>
               <td>Classes:</td>
               <td> <textarea name="class" rows="5" cols="40"></textarea></td>
            </tr>
           
            <tr>
               <td>Gender:</td>
               <td>
                  <input type="radio" name="gender" value="female">Female
                  <input type="radio" name="gender" value="male">Male
                  <span class="error">* <?php echo $genderErr;?></span>
               </td>
            </tr>
           
            <tr>
               <td>Select:</td>
               <td>
                  <select name="subject[]" size="4" multiple>
                     <option value="Android">Android</option>
                     <option value="Java">Java</option>
                     <option value="C#">C#</option>
                     <option value="Data Base">Data Base</option>
                     <option value="Hadoop">Hadoop</option>
                     <option value="VB script">VB script</option>
                  </select>
               </td>
            </tr>
           
            <tr>
               <td>Agree</td>
               <td><input type="checkbox" name="checked" value="1"></td>
               <?php if(!isset($_POST['checked'])){ ?>
               <span class="error">* <?php echo "You must agree to terms";?></span>
               <?php } ?>
            </tr>
           
            <tr>
               <td>
                  <input type="submit" name="submit" value="Submit">
               </td>
            </tr>
           
         </table>
      </form>
     
      <?php
         echo "<h2>Your given values are as :</h2>";
         echo ("<p>Your name is $name</p>");
         echo ("<p> your email address is $email</p>");
         echo ("<p>Your class time at $course</p>");
         echo ("<p>your class info $class </p>");
         echo ("<p>your gender is $gender</p>");
        
         for($i=0; $i < count($subject); $i++)
         {
            echo($subject[$i] . " ");
         }
      ?>
 </body>

</html>



(1)First write code for  "captcha.php"   file:

<?php
// Create our image
$image = imagecreatetruecolor(100, 30);

// Assign a background colour. I have set it to white but background is going to be transparent anyway
$background = imagecolorallocate($image, 0,0,0);

// Make background transparent by setting the colour we are going to use as transparent
imagecolortransparent($image, $background);

// Fill it in with the background colour. This is required to make the background transparent
imagefilledrectangle($image, 0, 0, 199, 49, $background);

// function to generate captcha characters
function captchaChars($hash)
{
  //  Generate a 32 character string by getting the MD5 hash of the servers name with the hash added to the end.
  //  Adding the servers name means outside sources cannot just work out the characters from the hash
  $captchastr = md5($_SERVER['SERVER_NAME'] . $hash);
  return strtoupper($captchastr); // Make all our characters uppercase for clarity in the image
}

// Lets get the characters to show in the image or say 'error' if no hash submitted
$str = (!empty($_GET['hash'])) ? captchaChars($_GET['hash']) : 'ERROR';

// Assign a colour for the text and lines. I've chosen a shade of grey
$our_colour = imagecolorallocate($image, 140,140,140);

// Lets add three random background lines
for ($i = mt_rand(5, 8); $i <= 29; $i += 10)
{
  imageline($image, mt_rand(0, 100), $i + mt_rand(-5, 5), mt_rand(0, 100), $i + mt_rand(-5, 5), $our_colour);
}

// Set a random horizontal starting position
$x_pos = mt_rand(10, 20);

// Lets loop through our string adding one character at a time in a randomish position
// We start with the first character and then use every seventh character just for added randomness
for($i = 0; $i <= 28; $i += 7)
{
  imagestring($image, 5, $x_pos, mt_rand(0, 12), $str[$i], $our_colour); // add a character from our string
  $x_pos += mt_rand(10, 18);  // Move the horizontal position by a random amount
}

// Add some wavy distortion to the image
$wave = rand(3,5);
$wave_width = rand(8,15);
for ($i = 0; $i < 200; $i += 2)
{
  imagecopy($image, $image, $i - 2, sin($i / $wave_width) * $wave, $i, 0, 2, 40);
}

// Send the gif header. We use a gif because of IE6's poor support for PNG transparency
header('Content-type: image/gif');
// Dump the image
imagegif($image);

?>



(2)Second write code for   "captchaform.php"  file:


<?php
$hash = substr(md5(mt_rand(1, 1000)), 10, 20); // Just generate a random hash to use
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8">
  <title></title>
  <script type="text/javascript">
  function reloadCaptcha(imageName)
  {
    var randomnumber=Math.floor(Math.random()*1001); // generate a random number to add to image url to prevent caching
    document.images[imageName].src = document.images[imageName].src + '&amp;rand=' + randomnumber; // change image src to the same url but with the random number on the end
  }
  </script>
  </head>
  <body>
<img src="captcha.php?hash=<?php echo $hash; ?>" alt="captcha" name="captchaImage"><br>
<a href="#" onclick="reloadCaptcha('captchaImage'); return false;">refresh image</a>
<form action="captchaform.php" method="post">
<input type="text" name="captchacode"><br>
<input type="submit" value="Submit Code" name="submit">
<input type="hidden" value="<?php echo $hash; ?>" name="hash">
</form>
<div style="height:20px;"> <?php
if(isset($_POST['submit']))
{
  $hash = (!empty($_POST['hash'])) ? preg_replace('/[\W]/i', '', trim($_POST['hash'])) : ''; // Remove any non alphanumeric characters to prevent exploit attempts
  $captchacode = (!empty($_POST['captchacode'])) ? preg_replace('/[\W]/i', '', trim($_POST['captchacode'])) : ''; // Remove any non alphanumeric characters to prevent exploit attempts
  // function to check the submitted captcha
  function captchaChars($hash)
  {
    //  Generate a 32 character string by getting the MD5 hash of the servers name with the hash added to the end.
    //  Adding the servers name means outside sources cannot just work out the characters from the hash
    $captchastr = strtolower(md5($_SERVER['SERVER_NAME'] . $hash));
    $captchastr2 = '';
    for($i = 0; $i <= 28; $i += 7)
    {
      $captchastr2 .= $captchastr[$i];
    }
    return $captchastr2;
  }
  if(!empty($captchacode))
  {
    if(strtolower($captchacode) == captchaChars($hash))  // We convert submitted characters to lower case then compare with the expected answer
    {
      echo '<h3>The submitted characters were correct</h3>';
    }
    else
    {
      echo '<h3>The submitted characters were WRONG!</h3>';
    }
  }
  else
  {
    echo '<h3>You forgot to fill in the code!</h3>';
  }
}
?>
</div>
  </body>
</html>

 Output:



Connectivity    Code   for MYSQL  DATABASE.

here in given below code  localhost is server name and root is username, password is ""(blank).
note: when we upload it on server then we require  following:

(1)databse server name.
(2)username. 
(3)password.
(4)database name.

<?php

$con=mysql_connect("localhost","root","");

mysql_select_db("needa",$con);

if($con)
{
echo  "connection is successful";
}
else
{
     echo "not connected";
}
?>

Insert   , update , delete ,search in   PHP :

First   OF ALL   create table   details  :
Create table details
(id     int    primary   key auto_increment ,
name     varchar(200),
city      varchar(200));

((1)    first      write code   for   insert.html :

<form   action="insert.php"      method="post">
<input type="text"     name="id">
<input type="text"    name="name">
<input type="text"     name="city">
<input     name="myBtn"       type="submit"        value="Submit Data">
</form>


 (2) write     code    for     insert.php  :

<?php
$id=$_POST['id'];
$nm=$_POST['name'];
$cy=$_POST['city'];
$con=mysql_connect('localhost','root','' );
mysql_select_db('needa',$con);
$sql="insert into details (id,name,city) values('$id','$nm','$cy')";
mysql_query($sql);
echo "record inserted successfully";

?>




Now write code for update in php:

(1)write     code     for      update.html  :
<form   action="update.php"      method="post">
<input type="text"       name="id">
<input type="text"       name="name">
<input type="text"       name="city">
<input name="myBtn" type="submit" value="Submit Data" >
</form>

(2)write    code     for     update.php       file:
<?php

$id=$_POST['id'];

$nm=$_POST['name'];

$cy=$_POST['city'];


$con=mysql_connect('localhost','root','' );

mysql_select_db('needa',$con);

$sql="update details set name ='$nm', city='$cy' where id='$id'";

mysql_query($sql);
echo "record updated successfully";
?>

Now write code   delete in php :

(1)write  code for delete.html:

<form     action="delete.php"        method="post">
<input type="text"       name="id">
<input name="myBtn" type="submit" value="Submit Data" >
</form>

( (2) write     code    for     “delete.php”     file :
<?php

$id=$_POST['id'];

$con=mysql_connect('localhost','root','' );

mysql_select_db('needa',$con);

$sql="delete from details where id='$id'";

mysql_query($sql);

echo "record deleted successfully";


?>


now      write     code    for    search      example    :

( (1)   write    code   for   search.html  :
<form   action="search.php"      method="post">
<input type="text"       name="name">
<input      name="myBtn"        type="submit"         value="Submit Data" >
</form>


(2)write   code for    search.php   :
<?php
$nm=$_POST['name'];
$con=mysql_connect('localhost','root','' );
mysql_select_db('needa',$con);
$sql="select * from details where name='$nm'";
$result=mysql_query($sql);
while($row=mysql_fetch_array($result))
{
echo $row['id'];
echo $row['name'];
echo $row['city'];

}


?>


UPDATE & DELETE USING HIDDEN CONCEPT:

(1)FIRST CREATE TABLE:
Create table record
(id   int,
name varchar(20),
email varchar(20),
password  varchar(20)
);
(2)
(2)Insert record into table for example :
insert record into (id,name,email,password)values(‘1’,’om’,’om@gmail.com’,’@1234’);

(3)write code for display.php:
<?php

  $con =mysql_connect("localhost","root","");
   mysql_select_db("bibhu",$con);
   $sql = "select * from record";
     $result = mysql_query($sql);
                 echo '<table border=1>
                 <tr> <td>id</td><td>name</td><td>email</td><td>password</td><td>&nbsp;</td><td>&nbsp;</td></tr>';
                while($row=mysql_fetch_array($result))
                { 
               
          echo '<tr>';
                                  echo '<td>';
                                  echo $row['id'];
                                  echo '</td>';
                                  echo '<td>';
                                  echo $row['name'];
                                  echo '</td>';
                                  echo '<td>';
                                  echo $row["email"];
                                  echo '</td>';
                                   echo '<td>';
                                  echo $row["password"];
                                  echo '</td>';
                                 
                                  echo '<td> <form action="update.php" method="post">
                                              <input type="hidden" name="hidden" value="'.$row['id'].'">
                                 
                                   <input type="submit"name="button" value="update">
                                  </form></td>';
                                  echo '<td> <form action="delete.php"method="post">
                                    <input type="hidden" name="hidden" value="'.$row['id'].'">
                                   <input type="submit"name="button"value="delete">
                                  </form></td>';
                                 
                                  echo'</tr>';
                                 
                                 
                                  }
                                 
                 echo'</table>';
?>


output : 


(4)write code for  “update.php”  file:
<?php
 $hidden=$_POST["hidden"];
 $con =mysql_connect("localhost","root","");
   mysql_select_db("bibhu",$con);
   $sql = "select * from record where id='$hidden'";
     $result = mysql_query($sql);
    while($row=mysql_fetch_array($result))
                {
                                echo '<form action="finalupdate.php" method="post">
                                id <input type="text" name="id"  value="'.$row['id'].'">
                                Name <input type="text" name="name"  value="'.$row['name'].'">
                                email <input type="text" name="email" value="'.$row['email'].'">
                                password<input type="text" name="password" value="'.$row['password'].'">
                               
                                <input type="hidden" name="hidden" value="'.$row['id'].'">
                                <input type="submit"value="update"name="update">
                                </form>';
                               
                               
                               
                               
                               
                }
?>

ouput:


(5)write code for  “finalupdate.php “:

<?php
 $hidden=$_POST["hidden"];
 $name=$_POST["name"];
 $email=$_POST["email"];
 $password=$_POST["password"];
   $con=mysql_connect("localhost","root","");
    mysql_select_db("bibhu",$con);
                $sql="update record set name='$name', email='$email',password='$password' where id='$hidden'";
                mysql_query($sql);
                echo"record updated successfully";
?>



(6)Now for delete write code for   “delete .php “  file:
<?php
 $hidden=$_POST["hidden"];
  $con=mysql_connect("localhost","root","");
    mysql_select_db("bibhu",$con);
                $sql="delete from record where id='$hidden'";
                mysql_query($sql);
                echo"record deleted successfully";
?>






PHP FILE HANDLING:
PHP Open File - fopen():
A better method to open files is with the fopen() function.

PHP Read File - fread():

The fread() function reads from an open file.

PHP Read Single Line - fgets():

The fgets() function is used to read a single line from a file.

PHP Write to File - fwrite():

The fwrite() function is used to write to a file.
r =>        Open a file for read only. File pointer starts at the beginning of the file
w=>       Open a file for write only. Erases the contents of the file or creates a new file if it doesn't exist. File pointer starts at the beginning of the file
a=>        Open a file for write only. The existing data in file is preserved. File pointer starts at the end of the file. Creates a new file if the file doesn't exist

(1)TO   WRITE   A   TEXT  “this is my file”    INTO   A  FILE  NAME IS   “abc.txt”  Code  is   use mode “w”:
<?php
$fhandle=fopen("abc.txt","w");
fwrite($fhandle,"this is my  file");
?>



(2) To read   text form  “abc.txt “ file  using filesize() & fread() function  use mode “r”:

<?php


$fhandle=fopen("abc.txt","r");


$line=fread($fhandle,filesize("abc.txt"));


echo $line;

?>

(3) To read   text form  “abc.txt “ file  using while loop  use mode “r”  :
<?php

$file = fopen("abc.txt", "r");


//Output a line of the file until the end is reached


while(! feof($file))

  {
  echo fgets($file). "<br />";
  }
fclose($file);


?>

(3)how to append new line to  file  “abc.txt”  just use mode “a” :

<?php

$fhandle=fopen("ok.txt","a");



fwrite($fhandle,"this is my file om maurya");



?>


PHP   FILE   UPLOADING  :

Create  Table   Upload
(id   int  primary key   auto_increment  ,
file     varchar(200));
then sart coding ..
(1)write code   "uploadform.html" :

<form  action="upload.php"     method="post"     enctype="multipart/form-data">
<input type="file"    name="file"   id="file" >
<input type=submit  name="upload"   value="upload">
</form>

Some rules to follow for the HTML form above:
  • Make sure that the form uses method="post"
  • The form also needs the following attribute: enctype="multipart/form-data". It specifies which content-type to use when submitting the form


(2)Second    write    code    for     “upload.php”   :

<?php

if(isset($_POST["upload"]))
{

$file=$_FILES["file"]["name"];

move_uploaded_file($_FILES["file"]["tmp_name"],"upload/".$_FILES["file"]["name"]);

$con=mysql_connect("localhost","root","");

mysql_select_db("data",$con);

$sql="insert into upload(file) values ('$file')";

mysql_query($sql);

}

?>
Note in above code   we used   move_uploaded_file();
and will upload inside  of  upload folder    (upload/".$_FILES["file"]["name"])

Sending email using   Php-Mail-function :


See below example  :
here $to =whom to send
$subject =subject of  email 
$message=it is message which you want to email
$header =from whom is message 
note :here php  mail () function is used to send email ...

<?php

   $to = "omchandmaurya1@gmail.com";
  
 
   $subject = "This is subject";
  
 
   $message = "This is simple text message.";
  
 
   $header = "From:omnetworkom@gmail.com \r\n";
  
 
   $retval = mail ($to,$subject,$message,$header);
  
 
   if( $retval == true ) 
 

   {

      echo "Message sent successfully...";

   }

   else

   {

      echo "Message could not be sent...";

   }

?>

PHP   SESSION  & LOGIN MODULE :

how to create a simple page-views  counter . The isset() function checks if the "views"  variable has already
been set. if "views" has been set, we can increment our counter. if  "views" doesn't  exist,we create a "views" variable and set it to 1:


<?php 
session_start();
if(isset($_SESSION['views']))
{

$_SESSION['views']=$_SESSION['views']+1;

}

else

{

$_SESSION['views']=1;

}

echo "views=".$_SESSION['views'];


?>


Login   Module   with   session   Management:

(1)First create   database   & table   &    Insert  values   for username & password:
Create  database    amrapali;  
Create table  user
(id   int  primary key auto_increment,
username   varchar(20),
password   varchar(20));

(1)    Write html code for  “Loginform.html”  file , CODE IS GIVEN BELOW:
<html>
<head>
<title>
login example
</title>
</head>
<body>
<form action="login.php"    method="post">

username <input type=text    name="username">

Password <input type=text name="password">

<input type="submit"   name="submit" value="submit">

</body>
</html>






(2)write php code  which will check username & password   “login.php”  file CODE IS GIVEN BELOW:
<?php

$con=mysql_connect("Localhost","root","");

mysql_select_db("amrapali",$con);

$username=$_POST['username'];

$password=$_POST['password'];

$sql="select  username , password from  user where username='$username' AND password='$password'";

$result=mysql_query($sql);

$num=mysql_num_rows($result);

if($num>0)
{

session_start();

$_SESSION['username']='$username';

header('Location:welcome.php');

}

else
{

echo "invalid login";

}

?>



(3)AFTER LOGIN  page will display that is  “welcome.php”:
<?php

session_start();

if(!isset($_SESSION['username']))
{

header("Location:error.php");

}


echo "<h1>welcome </h1>";


echo '<a href="logout.php">Logout</a>';




?>



(4) logout.php     file this file destroy session:
<?php

session_start();

session_destroy();

 header("Location:loginform.html");

?>

(5) error.php  file:

<?php

echo "first make login ";

echo '<a  href="loginform.html">Login here</a>';

?>





PHP   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.
·        Destructors: refers to a special type of function which will be called automatically whenever an object is deleted or goes out of scope.

Example   :

Here is an example which defines a   class of   Books     type  :
<?php
class  Books{
    /* Member variables */
    var $price;
    var $title;
    /* Member functions */
    function setPrice($par)
{
       $this->price = $par;
    }
    function getPrice(){
       echo $this->price ."<br/>";
    }
    function setTitle($par){
       $this->title = $par;
    }
    function getTitle(){
       echo $this->title ." <br/>";
    }
}
?>
The variable $this is a special variable and it refers to the same object ie.  itself.

Creating   Objects   in  PHP  :

 

Once you defined your class, then you can create as many objects as you like of that class type. Following is an example of how to create object using new operator.

$physics = new Books;
$maths = new Books;
$chemistry = new Books;

Here we have created three objects and these objects are independent of each other and they will have their existance separately. Next we will see how to access member function and process member variables.

Calling Member Functions

After creating your objects, you will be able to call member functions related to that object. One member function will be able to process member variable of related object only.
Following example shows how to set title and prices for the three books  by  calling  member  functions.
$physics->setTitle( "Physics for High School" );
$chemistry->setTitle( "Advanced Chemistry" );
$maths->setTitle( "Algebra" );
 
$physics->setPrice( 10 );
$chemistry->setPrice( 15 );
$maths->setPrice( 7 );

 

Constructor   Functions   :

 

Constructor Functions are special type of functions which are called automatically whenever an object is created. So we take full advantage of this behaviour, by initializing many things through constructor functions.
PHP provides a special function   called __construct()   to define a constructor. You can pass as many as arguments you like into the constructor function.
Following example will create one constructor for Books class and it will initialize price and title for the book at the time of object creation.

function __construct( $par1, $par2 ){
   $this->price = $par1;
   $this->title = $par2;
}

 

 

Destructor   :

 

Like a constructor function you can define a destructor function using function __destruct().  You can release all the resourceses with-in a destructor.
Example for constructor & Destructor  :

<?php
class   example
{

function   __construct()
{

echo "constructor is called & object  is created";
echo "<br>";

}

Function  __destruct()
{

echo "destructor is called & object is free";

}
}
$obj=new  example();

?>

Inheritance   :

 

PHP class definitions can optionally inherit from a parent class definition by using the extends clause. The syntax is as follows:
class Child extends Parent {
     <definition body>
  }
The effect of inheritance is that the child class (or subclass or derived class) has the following characteristics:
·        Automatically has all the member variable declarations of the parent class.
·        Automatically has all the same member functions as the parent, which (by default) will work the same way as those functions do in the parent.

<?php

class   parent1

{

var $name="test";
var $phone="123456";

public function disp()
{

echo $this->name;
echo "<br>";
echo $this->phone;

echo "<br>";

}
}

class   inheritance1  extends parent1
{

function read()
{

echo "it is working fine";

}


}

$obj=new   inheritance1();

$obj->disp();

$obj->read();


?>


 How to call parent class   constructor     parent::__construct();   :
<?php
class BaseClass {
   function __construct() {
       print "In BaseClass constructor\n";
   }
}

class SubClass extends BaseClass {
   function __construct()
   {
       parent::__construct();
       print "In SubClass constructor\n";
   }
}

//$obj = new BaseClass();
$obj = new SubClass();
?>


Function     Overriding  :

 

Function definitions in child classes override definitions with the same name in parent classes. In a child class, we can modify the definition of a function inherited from parent class.

<?php
class abc
{
var $a;
var $b;
function cal($p,$q)
{
$this->a=$p;
$this->b=$q;
$sum=$this->a+$this->b;
echo"it is addition of two parameters".$sum;
}
}
class xyz extends abc
{
var $a;
var $b;
var $c;
var $d;
function cal($p,$q)
{
$this->a=$p;
$this->b=$q;

$sum=$this->a*$this->b;
echo"multiplication of two parameters".$sum;
}

}
$obj=new xyz();
$obj->cal(5,2);

?>



Function    Overloading   using    function __call :

<?php

 

class test12

 

{

    public function __call($name, $arguments)

               

    {

        if ($name === 'test'){

            if(count($arguments) === 1 ){

                return $this->test1($arguments[0]);

            }

            if(count($arguments) === 2){

                return $this->test2($arguments[0], $arguments[1]);

            }

                                                if(count($arguments) === 3){

                return $this->test3($arguments[0], $arguments[1],$arguments[2]);

            }

 

        }

    }

 

    private function test1($data1)

    {

       echo $data1;

    }

 

    private function test2($data1,$data2)

    {

       echo $data1.' '.$data2;

    }

                 private function test3($data1,$data2,$data3)

    {

       echo $data1.' '.$data2.$data3;

    }

}

 

$test = new test12();

 

$test->test('one argument');                //echoes "one argument"

 

$test->test('two','arguments');

 

$test->test('three','om','test');          //echoes "two arguments"

 

 

?>

 

Public Members   :

 

Unless you specify otherwise, properties and methods of a class are public. That is to say, they may be accessed in three possible situations:
·        From outside the class in which it is declared
·        From within the class in which it is declared
·        From within another class that implements the class in which it is declared
Till now we have seen all members as public members. If you wish to   limit   the   accessibility    of    the    members   of   a   class   then    you    define   class      members    as    private.
<?php
class  books
{

var  $bookname;
var  $price;

function display($name, $cost)
{
echo $this->bookname=$name;
echo '<br>';
echo $this->price=$cost;
echo '<br>';

}
}

$obj=new books();
$obj->display("om",10);
?>

Interfaces   :

 

Interfaces are defined to provide a common function names to the implementors. Different implementors can implement those interfaces according to theri requirements. You can say, interfaces are skeltons which are implemented by developers.
As of PHP5, it is possible to define an interface, like   this  :

interface Mail {
   public function sendMail();
}

Then, if another class implemented that interface, like   this :

class Report implements Mail {
   // sendMail() Definition goes here
}
Example :
<?php

interface  test

{

function disp();

}

class  hello implements test
{


function disp()
{


echo "it is interface function";


}


}

$obj=new  hello();


$obj->disp();


?>

Constants   :


A constant is somewhat like a variable, in that it holds a value, but is really more like a function because a constant is immutable. Once you declare a constant, it does not change.
Declaring one constant is easy, as is done in this version of   MyClass  :

class MyClass {
   const requiredMargin = 1.7;
   function __construct($incomingValue) {
      // Statements here run every time
      // an instance of the class
      // is created.
   }
}


Class      Constants  :

It is possible to define constant values on a per-class basis remaining the same and unchangeable. Constants differ from normal variables in that you don't use the $ symbol to declare or use them. Like static members, constant values cannot be accessed from an instance of the object (using $object::constant).
The value must be a constant expression, not (for example) a variable, a class member, result of a mathematical operation or a function call.
Example : Defining and using a constant
<?php
class MyClass
{
    const constant = 'constant value';
 
    function showConstant() {
        echo  self::constant . "\n";
    }
}
 
echo MyClass::constant . "\n";
 
$class = new MyClass();
$class->showConstant();
// echo $class::constant;  is not allowed
?>

Abstract   Classes  :

An abstract class is one that cannot be instantiated, only inherited. You declare an abstract class with the keyword abstract, like this :
When inheriting from an abstract class, all methods marked abstract in the parent's class declaration must be defined by the child; additionally, these methods must be defined with the same visibillity.

abstract class MyAbstractClass {
   abstract function myAbstractFunction() {
   }
}
Example :
<?php

abstract        class       Animal
{
    public $name;
    public $age;
   
    public function Describe()
    {
        return $this->name . ", " . $this->age . " years old";   
    }
   
    abstract public function Greet();
}

class Dog extends Animal
{
    public function Greet()
    {
        return "Woof!";   
    }
   
   
}

$animal = new Dog();
$animal->name = "Bob";
$animal->age = 7;
echo $animal->Describe();
echo $animal->Greet();

?>

Static         Keyword    :   

 

Declaring class members or methods as static makes them accessible without needing an instantiation of the class. A member declared as static   can   not   be accessed with an instantiated class object (though a static method can).
Example :
<?php

Class  staticexample
{

public   static   $name="om";           // static variable


public static function disp()      //static member function


{

echo "static member function is this";


}


}


$obj=new   staticexample();


print  staticexample::$name;       // accessing static variable

echo "<br>";

staticexample::disp();            //accessing static member function





?>

Final    Keyword   :


PHP 5 introduces the final keyword, which prevents child classes from overriding a method by prefixing the definition with final. If the class itself is being defined final then it cannot be extended.
Following example results in Fatal error: Cannot override final method BaseClass::moreTesting()
<?php
class BaseClass {
   public function test() {
       echo "BaseClass::test() called<br>";
   }
  
   final public function moreTesting() {
       echo "BaseClass::moreTesting() called<br>";
   }
}
 
class ChildClass extends BaseClass {
   public function moreTesting() {
       echo "ChildClass::moreTesting() called<br>";
   }
}
?>

Parent    keyword   :
<?php
class A
{
    function example()
           {

        echo "I am A::example() and provide basic functionality.<br />\n";
    }
}

class B extends A  {
    function example() {
        echo "I am B::example() and provide additional functionality.<br />\n";
        parent::example();
    }
}

$b =new B;


// This will call B::example(),    which will in turn call A::example().


$b->example();

?>

SOME EXAMPLES TO USE OBJECT ORIENTED  PROGRAMMING IN PHP FOR INSERT,UPDATE ,DELETE ,SEARCH & DISPLAY RECORD:


(1)create table example:

create table example
(id int,
name  varchar(200));


(2)write code for     “ connect.php ”  :

<?php
class db
{
var $host='localhost';
var $username='root';
var $password='';
var $connection;
var $database;
function __construct()
{
$this->connection=mysql_connect($this->host,$this->username,$this->password);
if($this->connection)
{
Echo   "connection successful";
echo    "<br>";
}
else
{
echo"connection error";
echo"<br>";
}
}
}
$obj=new db();
?>

(2)write code for   form.html:

<form action=”insert.php “  method=”post”>
Id<input type=text      name=id>
Name <input type=text     name=name>
</form>


 (3)write  code   for    “insert.php”    :

<?php

Class  db
{
var $host="localhost";
var $username="root";
var $password="";
var $database="amrapali";
var $connection;
function __construct()
{
$this->connection=mysql_connect($this->host,$this->username,$this->password);
if($this->connection)
{
echo"connected successfully";
}
else
{
echo"connection failed";
}
mysql_select_db($this->database,$this->connection);
}

function  insert()
{
$id=$_POST[‘id’];
$name=$_POST['name'];
$sql="insert   into   example(id,name) values(‘$id’,’$name’)";
mysql_query($sql);
}
}
$obj=new db();
$obj->insert();
?>


(4)  write code for  updateform.html   :

<form action=”update.php “      method=”post”>
Id<input type=text      name=id>
Name <input type=text     name=name>
</form>

(5)write  code  update.php  :

<?php

class   db
{

var $host="localhost";
var $username="root";
var $password="";
var $database="amrapali";
var $connection;
function __construct()

{

$this->connection=mysql_connect($this->host,$this->username,$this->password);
if($this->connection)
{

echo"connected successfully";

}
else
{
echo"connection failed";
}
mysql_select_db($this->database,$this->connection);
}

function   update()
{
$id=$_POST[‘id’];
$name=$_POST['name'];
$sql="update example    set   id='$id'   where name='$name' ";
mysql_query($sql);

}

}
$obj=new db();
$obj->update();
?>

(6)Write   code   for   “delete.html” file   :

<form action=”delete.php “      method=”post”>

Id<input type=text      name=id>
</form>


(7)write    code for  "delete.php" file  :

<?php
class db
{
var $host="localhost";
var $username="root";
var $password="";
var $database="amrapali";
var $connection;
function __construct()
{
$this->connection=mysql_connect($this->host,$this->username,$this->password);
if($this->connection)
{
echo"connected successfully";
}
else
{
echo"connection failed";
}
mysql_select_db($this->database,$this->connection);
}
function delete()
{
$id=$_POST["id"];
$sql="delete from example where id='$id'";
mysql_query($sql);
}
}
$obj=new db();
$obj->delete();
?>


(7)write code for display form table record:

<?php
class db
{
var $host="localhost";
var $username="root";
var $password="";
var $database="amrapali";
var $connection;
function __construct()
{
$this->connection=mysql_connect($this->host,$this->username,$this->password);
if($this->connection)
{
echo"connected successfully";
}
else
{
echo"connection failed";
}
mysql_select_db($this->database,$this->connection);
}
function display()
{
$sql="select * from example";
$result=mysql_query($sql);
while($row=mysql_fetch_array($result))
{
echo $row['id'];
echo $row['name'];
echo"<br>";
}
}
}
$obj=new db();
$obj->display();
?>




Ajax   with    PHP  &  MYSQL   Database :



PHP  Ajax :

What is AJAX ?.....

AJAX stands for Asynchronous JavaScript and  XML.

AJAX is a new technique for creating better, faster, and...

more interactive web applications with the help of XML, HTML, CSS and Java Script.

Conventional web application trasmit information to and from the sever using synchronous requests.

This means you fill out a form,

hit submit,and get directed to a new page with new information from the server.

With AJAX when submit is pressed, JavaScript will make a request to the server,

interpret the results and update the current screen. In the purest sense,



the user would never know that anything was even transmitted to the server.

FIRST CREATE  TABLE    details :
create table  details
(id  int,
name   varchar(200),
city    varchar(200));



Ajax example code  for   inserting record from  form   to MYSQL  Database :


(1)first write code for  insert.html   file:
<html>
<head>
<script>
function ajax_post()
{
    // Create our XMLHttpRequest object
    var hr = new XMLHttpRequest();
     
    // Create some variables we need to send to our PHP file
     
    var url = "insert.php";
     
    var id = document.getElementById("id").value;
     
    var nm = document.getElementById("name").value;
     
      var cy = document.getElementById("city").value;
     

     

    var vars = "id="+id+"&name="+nm+"&city="+cy;
     
    hr.open("POST", url, true);
    // Set content type header information for sending url encoded variables in the request
    hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    // Access the onreadystatechange event for the XMLHttpRequest object
    hr.onreadystatechange = function() {
          if(hr.readyState == 4 && hr.status == 200) {
                      var return_data = hr.responseText;
                              document.getElementById("status").innerHTML = return_data;
          }
    }
    // Send the data to PHP now... and wait for response to update the status div
    hr.send(vars); // Actually execute the request
    document.getElementById("status").innerHTML = "processing...";
}
</script>
</head>
<body>
<input type="text" id="id" name="id">
<input type="text" id="name" name="name">
<input type="text" id="city" name="city">
<input name="myBtn" type="submit" value="Submit Data" onclick="ajax_post();">
<div id="status"></div>
</body>
</html>


(2)Then    write    code   for     insert.php   :
<?php
$id=$_POST['id'];
$nm=$_POST['name'];
$cy=$_POST['city'];
$con=mysql_connect('localhost','root','' );
mysql_select_db('needa',$con);
$sql="insert into details (id,name,city) values('$id','$nm','$cy')";
mysql_query($sql);
echo "record inserted successfully";


?>

Ajax example code   to   update record   from    form   to MYSQL   Database   :
(1) write   code for    update.html  :
<html>
<head>
<script>
function ajax_post()
{
    // Create our XMLHttpRequest object
    var hr = new XMLHttpRequest();
     
    // Create some variables we need to send to our PHP file
     
    var url = "update.php";
     
    var id = document.getElementById("id").value;
     
    var nm = document.getElementById("name").value;
     
      var cy = document.getElementById("city").value;
     

     

    var vars = "id="+id+"&name="+nm+"&city="+cy;
     
    hr.open("POST", url, true);
    // Set content type header information for sending url encoded variables in the request
    hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    // Access the onreadystatechange event for the XMLHttpRequest object
    hr.onreadystatechange = function() {
          if(hr.readyState == 4 && hr.status == 200) {
                      var return_data = hr.responseText;
                              document.getElementById("status").innerHTML = return_data;
          }
    }
    // Send the data to PHP now... and wait for response to update the status div
    hr.send(vars); // Actually execute the request
    document.getElementById("status").innerHTML = "processing...";
}
</script>
</head>
<body>
<input type="text" id="id" name="id">
<input type="text" id="name" name="name">
<input type="text" id="city" name="city">
<input name="myBtn" type="submit" value="Submit Data" onclick="ajax_post();">
<div id="status"></div>
</body>
</html>
(2)write    code   for   update.php  :
<?php
$id=$_POST['id'];
$nm=$_POST['name'];
$cy=$_POST['city'];
$con=mysql_connect('localhost','root','' );
mysql_select_db('needa',$con);
$sql="update details set name ='$nm', city='$cy' where id='$id'";
mysql_query($sql);
echo "record updated successfully";

?>



Ajax example code   to   search record   from       MYSQL   Database   :
(1)write   code search.html :
<html>
<head>
<script>
function ajax_post()
{
    // Create our XMLHttpRequest object
    var hr = new XMLHttpRequest();
           
    // Create some variables we need to send to our PHP file
           
    var url = "search.php";
           

           
    var nm = document.getElementById("name").value;
           

           

           

    var vars = "name="+nm;
           
    hr.open("POST", url, true);
    // Set content type header information for sending url encoded variables in the request
    hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    // Access the onreadystatechange event for the XMLHttpRequest object
    hr.onreadystatechange = function() {
                if(hr.readyState == 4 && hr.status == 200) {
                            var return_data = hr.responseText;
                                    document.getElementById("status").innerHTML = return_data;
                }
    }
    // Send the data to PHP now... and wait for response to update the status div
    hr.send(vars); // Actually execute the request
    document.getElementById("status").innerHTML = "processing...";
}
</script>
</head>
<body>
<input type="text" id="name" name="name">
<input name="myBtn" type="submit" value="Submit Data" onclick="ajax_post();">
<div id="status"></div>
</body>
</html>


(2)write  code for search.php:
<?php
$nm=$_POST['name'];
$con=mysql_connect('localhost','root','' );
mysql_select_db('needa',$con);
$sql="select * from details where name='$nm'";
$result=mysql_query($sql);
while($row=mysql_fetch_array($result))
{
echo $row['id'];
echo $row['name'];
echo $row['city'];

}
?>







Ajax example code   to     Delete    record   from       MYSQL   Database   :
(1)write    code   for   delete.html  :
<html>
<head>
<script>
function ajax_post()
{
    // Create our XMLHttpRequest object
    var hr = new XMLHttpRequest();
           
    // Create some variables we need to send to our PHP file
           
    var url = "delete.php";
           
    var id = document.getElementById("id").value;
           
    var vars = "id="+id;
           
    hr.open("POST", url, true);
    // Set content type header information for sending url encoded variables in the request
    hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    // Access the onreadystatechange event for the XMLHttpRequest object
    hr.onreadystatechange = function() {
                if(hr.readyState == 4 && hr.status == 200) {
                            var return_data = hr.responseText;
                                    document.getElementById("status").innerHTML = return_data;
                }
    }
    // Send the data to PHP now... and wait for response to update the status div
    hr.send(vars); // Actually execute the request
    document.getElementById("status").innerHTML = "processing...";
}
</script>
</head>
<body>
<input type="text" id="id" name="id">
<input name="myBtn" type="submit" value="Submit Data" onclick="ajax_post();">
<div id="status"></div>
</body>
</html>


(2) write  code for   delete.php  :

<?php
$id=$_POST['id'];
$con=mysql_connect('localhost','root','' );
mysql_select_db('needa',$con);
$sql="delete from details where id='$id'";
mysql_query($sql);
echo "record deleted successfully";

?>


(1)FIRST WRITE javascript CODE in <head> section </head> :
<html>
 <head>

<script type="text/javascript">
function doDelete(id){
if(confirm("Do you want to delete the record?")){
$.ajax({
url:'delete.php',
type:'post',
data:'id='+id,
success:function(msg){
alert(msg);
window.location.href='pagination2.php';
}
});
}
}
</script>

</head>

<!---Second  use  following line where you want to call doDelete() method in <body> section </body>--->
<body>
<?php

   include("connect.php");
  
    $per_page = 8;

    $pages_query = mysql_query("SELECT COUNT('id') FROM  notes order by coursename,semester ASC");

    $pages = ceil(mysql_result($pages_query, 0) / $per_page);

   
    $page = (isset($_GET['page'])) ? (int)$_GET['page'] : 1;
    $start = ($page - 1) * $per_page;
   
    $query = mysql_query("SELECT *  FROM notes LIMIT $start, $per_page");

while($row = mysql_fetch_assoc($query))


{

echo "record one";

?>



<a class="click-more" href="#" onClick="doDelete('<?php echo $row['id']; ?>');">read more</a>


<?php




$prev = $page - 1;
    $next = $page + 1;
   
    if(!($page<=1)){
        echo "<a href='pagination1.php?page=$prev'><button>Prev</button></a> ";
    }

    if($pages>=1 && $page<=$pages){
   
        for($x=1;$x<=$pages;$x++){
            echo ($x == $page) ? '<strong><a href="?page='.$x.'"><button>'.$x.'</button></a></strong> ' : '<a href="?page='.$x.'"><button>'.$x.'</button></a> ';
       
        }
   
    }
   
    if(!($page>=$pages)){
        echo "<a href='pagination1.php?page=$next'><button>Next>></button></a>";
    }
   
   
?>

</body>
</html>


(2)write code for "delete.php" file:

<?php

$id=$_POST['id'];

include("connect.php");


$sql="delete from notes where id='$id'";

mysql_query($sql) or die(mysql_error());


echo "Record deleted successfully";

echo '<br></br>';

echo '<a href="pagination1.php"><button>back to previous page</button></a>';


?>





Written by

We are Creative Blogger Theme Wavers which provides user friendly, effective and easy to use themes. Each support has free and providing HD support screen casting.

0 comments:

Post a Comment

PHP Training Mumbai, PHP MySQL Training Mumbai, PHP Course Mumbai, PHP Institute Mumbai

 

© 2013 PHP TRAINING IN MUMBAI BY OM SIR . All rights resevered. Designed by OM SIR

Back To Top