Sunteți pe pagina 1din 90

Website: Collection of web page.

Web Page: Collection of Hypertext.


Hypertext: Collection of text, formatted text, Images, Audio, Video, hyperlink for other
pages etc.

There are two types of web sites:


1) Static
2) Dynamic
There are two major differences between static and dynamic web sites:
1) The contents of static web site remain same but the contents of dynamic web sites
may be changed time to time or user to user.
2) User cannot interact with static web site but user interaction is allowed in dynamic
web site with limited authorization.

PHP Introduction(PHP Hypertext Preprocessor)

PHP is a powerful tool for making dynamic and interactive Web pages. PHP is a
server-side scripting language (scripts are executed on the server) like ASP.Net.

History
Rasmus Lerdorf inception in 1994

Features of PHP
1) PHP runs on different platforms (Windows, Linux, Unix, etc.)
2) PHP is compatible with almost all servers used today (Apache, IIS (Internet
Information Services), etc.)
3) PHP supports many databases (MySQL, Informix, Oracle, Sybase, Solid,
PostgreSQL, Generic ODBC, etc.)
4) PHP is open source software
5) PHP is FREE to download from the official PHP resource
6) PHP is easy to learn and runs efficiently on the server side

WAMP & LAMP Technology: WAMP or LAMP is a package which stands for:
WAMP LAMP
W : Windows (Operating System) L : Linux
A : Apache (Server Name) A : Apache
M : MySQL (Database) M : MySQL
P : PHP P : PHP
What is a PHP File?

Page 1 / 86
PHP files can contain text, HTML tags and scripts
PHP files are returned to the browser as plain HTML
PHP files have a file extension of ".php", ".php3"

Where to Start?
The official PHP website (PHP.net) has installation instructions for PHP:
http://php.net/manual/en/install.php or http://windows.php.net/download/
After download you will get below file:

To get access to a web server with PHP support, you can:


 Install Apache (or IIS) on your own server, install PHP, and MySQL
 Suppose if you installed WAMP Server in D: Drive then you have folder named
“wamp” in your D drive and you will find “www” folder in that “wamp” folder. So
create your folders in “www” and keep all the files in that folders.

Basic PHP Syntax (Scripting Tags)


A PHP script always starts with

<?php
[Statement;]
?>

A PHP script can be placed anywhere in the document. You can also start a PHP script
with

<?
[Statement;]
?>

Or script with

<%
[Statement;]
%>
<script language="php">

Page 2 / 86
echo "iBirds College";
</script>

<?= [Statement;] ?> (Shorthand tag)

<script language="php">
echo "Welcome to <b><u>iBirds</u></b> College"."<br/>";
print "M-15, Near City Hospital<br/>";
</script>

<?php
$num = 97;
printf("value of num is : %c", $num);
?>

A PHP file must have a .php extension. A PHP file normally contains HTML tags, and
some PHP scripting code. Below, we have an example of a simple PHP script that sends
the text "Hello World" back to the browser:

<?php
echo "Hello Everybody<br/>";
print "Welcome to iBirds College";
?>
PHP echo, print and printf 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 faster than print.

echo Statement
The echo statement can be used with or without parentheses: echo or echo().

Display Text
The following example shows how to output text with the echo command (notice that the
text can contain HTML markup):

Example

Page 3 / 86
<?php
echo "<h2>PHP is Fun!</h2>";
echo "Hello world!<br/>";
echo "This ", "string ", "was ", "made ", "with multiple parameters.<br/>";
echo ("This is another way for using echo");
?>

Display Variables
The following example shows how to output text and variables with the echo statement:

Example

<?php
$txt1 = "Learn PHP";
$txt2 = "iBirds College";
$x = 5;
$y = 4; printf("%d
echo $txt1."<br/>";
echo "Study PHP at $txt2<br/>";
echo $x + $y;
?>
Output:
Learn PHP
Study PHP at iBirds College
9
The PHP print Statement
The print statement can be used with or without parentheses: print or print().

Display Text
The following example shows how to output text with the print command (notice that the
text can contain HTML markup):

Example

<?php
print "<h2>PHP is Fun!</h2>";
Page 4 / 86
print "Hello world!<br/>";
print "I'm about to learn PHP!<br/>";
print ("This is another text");
?>
Output
PHP is Fun!
Hello world!
I'm about to learn PHP!
This is another text

Display Variables
The following example shows how to output text and variables with the print statement:

Example
<?php
$txt1 = "Learn PHP";
$txt2 = "iBirds College";
$x = 5;
$y = 4;
print "<h2>$txt1</h2>";
print "Study PHP at $txt2<br>";
print $x + $y;
print("<br/>Welcome");
?>
Output
Learn PHP
Study PHP at iBirds College
9
Welcome
Comments in PHP
In PHP, we use // or # to make a one-line comment or /* */ for block of comments

<?php
// echo This is single line comment
#print("This is another comment");
echo "This is not comment";
/* echo "This is block of comments";
echo "These lines will not print";*/
?>

Page 5 / 86
<?php
$msg = "Hello";
printf("%s",$msg);
$num = 329.3883;
printf("<br/>%.2f",$num);
printf("<br/>%c",65);
printf("<br/>%d",78)."<br/>";
for($i=65; $i<=90; $i++)
{
printf("%c",$i);
echo "<br/>";
}
?>

Output
This is not comment

PHP Data Types

A data type in a programming language is a set of data with values having predefined
characteristics. Data types are used for classification of data, validation and consumption
of memory.
Variables can store data of different types, and different data types can do different things.
PHP is a dynamic type language, means you don't need to specify type of the variable
because it is dynamically used by PHP. You need to use $sign to specify the data type. It
can hold any type of values such as numbers, strings etc. PHP supports the following data
types:
1) String 2) Integer 3) Float 4) Boolean 5) NULL 6) Array 7) Object
1) 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."<br>";
echo $y;
?>

Page 6 / 86
2) Integer : An integer is a whole number (without decimals).  It is a number between
-2,147,483,648 and +2,147,483,647.
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);
?>

3) Float : Float (floating point numbers - also called double)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);
?>

4)Boolean : A Boolean represents two possible states: TRUE or FALSE.Booleans are


often used in conditional testing.
<?php
$x = true;
$y = false;
var_dump($x);
var_dump($y);
?>

4)NULL : 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.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:
<?php
$x = "Hello world!";
$x = null;
var_dump($x);
?>

Page 7 / 86
5)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);
?>

6)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
$obj = new Car();
// show object properties
echo $obj->model;
?>

Tokens: Smallest individual unit in a language is called tokens. Tokens are categorized
as one of five classes that describe their functions (Keywords, identifiers,
separators, constants and operators) in accordance with the rules of the
programming language.

1) Keywords : In the PHP programming language, a keyword is a word that has a


predefined meaning in the language, because of this, programmers cannot
use keywords as names for variables, arrays, functions, classes or any
other identifiers.
Keywords are: echo, print, if, else, elseif, switch, case, while, do, for,
foreach, continue, break, array, include, include_once, require,
require_once, global, and, as, class, clone, default, abstract, try, catch,
declare, die, empty, exit, final, finally, function, goto, implements,
Page 8 / 86
interface, isset, list, namespace, new or, private, protected, public, return,
static, try, catch, throw, unlink, unset, use, var, xor, yieldetc.

2) Identifier : In PHP, identifiers are names given to PHP entities such as variable,
array, class, function etc. (pre define or user define)
Naming convention of Identifiers:
a) An identifier name must start with a letter or underscore. It will not
start with number.
b) An identifier cannot be a keyword.
c) An identifier name can only contain alpha-numeric characters and
underscores (A-z, 0-9, and _ ). We can't use special characters like +,
-, *, /, %, white space etc.
d) Identifiers names are case sensitive in PHP ($num and $Num are two
different variables)

Valid Name Invalid Name


$num2 $2num
$_9num $924
$printArray = array() $print = array()
$array = array()
$first_name $first-name

$house_number $house number

$__age__ $student'sName

3) Separator : Separators help define the structure of a program. It is used to


separate one statement to another or one block of code to another.
The separators are:
( ){ }:; , .

4) Escape Sequence : (also called escape characters or escape codes) in general they are
used to signal an alternative interpretation of a series of characters.
In PHP, a character preceded by a backslash (\) is an escape
sequence and has special meaning to the PHP. When an escape
sequence is encountered in a print statement, the compiler
interprets it accordingly. For example, if you want to put quotes
within quotes you must use the escape sequence, \", on the interior
quotes.

Page 9 / 86
To print the sentence: Welcome to "iBirds" College you should
write:echo "Welcome to \"iBirds\" College";

Escape Sequences in PHP


\n - New Line \t - Tab \" - Double Quote
\\ - Backslash \$ - Dollar Sign
5) Variable : (Name of memory location) Variables are simply names used to refer to
some location in memory – a location that holds a value with which we are
working. It may help to think of variables as a placeholder for a value. You
can think of a variable as being equivalent to its assigned value.
All variables in PHP are denoted with a leading dollar sign ($).
<?php
$num=10;
var_dump($num);
$name="iBirds College";
var_dump($name);
$value=3.14;
var_dump($value);
$married=true;
var_dump($married);
?>
Output will be
int10
string'iBirds College'(length=14)
float3.14
booleantrue

6)Constants : Constants are like variables except that once they are defined they cannot
be changed or undefined.
We can define constant with const keyword before variable name without
$ sign or use the define() function.
Example : const ABC='iBirds'; echo ABC;

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
<?php
define("GREETING", "Welcome to iBirds College");
echo GREETING;

Page 10 / 86
?>
The example below creates a constant with a case-insensitivename:
<?php
define("GREETING", "Welcome to iBirds College", true);
echo Greeting;
?>
7) Operator : An operator, in PHP, is a special symbol performing specific operations
on one, two or three operands and then returning a result. PHP operators
are generally used to manipulate primitive data types. The PHP operators
are classified into different categories: arithmetic, assignment, compound
assignment, relational, logical, bitwise andconcatenation operators.

a) Binary Operators – It works on two operands.


1. Arithmetical Operators : +, -, /, *, %
<?php
$num1=10;$num2= 5;
echo $num1+$num2."<br/>"; //15
echo $num1-$num2."<br/>"; //5
echo $num1*$num2."<br/>"; //50
echo $num1/$num2."<br/>"; //2
echo $num1%$num2."<br/>"; //0
echo (7%15)."<br/>"; //7
?>

Q) WAP to print sum of 3 digit integer number using arithmetical operators.


Q) WAP to print reverse of 3 digit integer number.
Q) WAP to find whether 3 digit integer number is palindrome or not. (using if)

2. Assignment Operator : =

3. Compound Assignment Operator :+=, -=, /=, *=, %= (Shorthand Operator)

<?php
$num = 10;
$num+=5;
echo $num."<br/>"; //15
$num-=2;
echo $num."<br/>"; //13
$num*=2;
echo $num."<br/>"; //26
Page 11 / 86
$num/=2;
echo $num."<br/>"; //13
$num%=5;
echo $num."<br/>"; //3
?>

4. Relational Operator : >, <, >=, <=, ==, !=

<?php
$num1 = 10;$num2 = 5;$num3=10;
echo ($num1>$num2)."<br/>"; // true (1)
echo ($num1<$num2)."<br/>"; //false (empty string)
echo ($num1>=$num3)."<br/>"; // true (1)
echo ($num3<=$num2)."<br/>"; //false (empty string)
echo ($num1==$num3)."<br/>"; //true (1)
echo ($num1!=$num2)."<br/>"; //true (1)
echo ($num1!=$num3)."<br/>"; //false (empty string)
?>

5. Logical Operator : && (and) || (or) ! (not)

Logical Operator && (and)


Truth Table (&&)
First Second Result
Condition Condition
T T T
T F F
F T F
F F F

<?php
$a=500;$b=100;$c=200;
echo $a>$b && $a>$c; //Result true
?>

<?php
$a=500;$b=100;$c=200;
echo $a>$b && $b>$c; //Result false
?>
<?php
Page 12 / 86
$a=500;
$b=100;
$c=200;
echo $a<$b && $a>$c; //Result false
?>

<?php
$a=500;
$b=100;
$c=200;
$a<$b && $a<$c; //Result false
?>

Logical Operator || (or)


Truth Table (||)
First Second Result
Condition Condition
T T T
T F T
F T T
F F F

<?php
$a=500;$b=100;$c=200;
echo $a>$b || $a>$c; //Result true
?>

<?php
$a=500;
$b=100;
$c=200;
echo $a>$b || $b>$c; //Result true
?>

<?php
$a=500;
$b=100;
$c=200;
echo $a<$b || $a>$c; //Result true ?>

Page 13 / 86
<?php
$a=500;
$b=100;
$c=200;
echo $a<$b || $a<$c; //Result false
?>
Logical Operator ! (not)
<?php
$a=500;$b=100;
echo !$a<$b; //Result 1 (true)
?>

<?php
$a=500;$b=100;
echo !$a>$b; //Result empty string (false)
?>

6. Bitwise Operator : Bitwise operations are necessary for much low-level


programming, such as writing device drivers, low-level
graphics, communications protocol packet assembly and
decoding. It looks directly at the binary digits or bits of an
integer.
&(and), | (or), ^ (XOR), << (left shift), >> (right shift)

Bitwise Operator & (and)


Truth Table (&)
First Second Result
Number Number
1 1 1
1 0 0
0 1 0
0 0 0

<?php
echo 27&7; //Result 3 echo 47&17; //Result 1
?>

Bit pattern
128 64 32 16 8 4 2 1
0 0 0 0 0 0 0 0
Page 14 / 86
Binary number of 27 is 00011011
Binary number of 7 is 00000111

(we will apply the truth table of bitwise operator &)

128 64 32 16 8 4 2 1 Binary to
Decimal
0 0 0 1 1 0 1 1 27
0 0 0 0 0 1 1 1 7
0 0 0 0 0 0 1 1 3

128 64 32 16 8 4 2 1 Binary to
Decimal
0 0 1 0 1 1 1 1 47
0 0 0 1 0 0 0 1 17
0 0 0 0 0 0 0 1 1

Bitwise operator | (or)


Truth Table (|)
First Second Result
Number Number
1 1 1
1 0 1
0 1 1
0 0 0

<?php
echo 27|7; //Result 31 echo 47|17; //Result 63
?>

(we will apply the truth table of bitwise operator | )

128 64 32 16 8 4 2 1 Binary to
Decimal
0 0 0 1 1 0 1 1 27
0 0 0 0 0 1 1 1 7
0 0 0 1 1 1 1 1 31
Page 15 / 86
128 64 32 16 8 4 2 1 Binary to
Decimal
0 0 1 0 1 1 1 1 47
0 0 0 1 0 0 0 1 17
0 0 1 1 1 1 1 1 63
Bitwise operator ^ (XOR)
Truth Table (^)
First Second Result
Number Number
1 1 0
1 0 1
0 1 1
0 0 0

<?php
echo 27^7; //Result 28 echo 47^17; //Result 62
?>

(we will apply the truth table of bitwise operator ^)


128 64 32 16 8 4 2 1 Binary to
Decimal
0 0 0 1 1 0 1 1 27
0 0 0 0 0 1 1 1 7
0 0 0 1 1 1 0 0 28

128 64 32 16 8 4 2 1 Binary to
Decimal
0 0 1 0 1 1 1 1 47
0 0 0 1 0 0 0 1 17
0 0 1 1 1 1 1 0 62

Bitwise operator << (Left Shift)

<?php
echo 21<<1; //Result 42 echo 192<<1; //Result 384
?>
0 0 0 1 0 1 0 1 --> 21 1 1 0 0 0 0 0 0 --> 192
Result 0 0 0 1 0 1 0 1 0 --> 42 1 1 0 0 0 0 0 0 0 --> 384
<?php
Page 16 / 86
echo 10<<3; //Result 80 echo 240<<2; //Result 960
?>
0 0 0 0 1 0 1 0 --> 10 1 1 1 1 0 0 0 0 --> 240
Result 0 0 0 0 1 0 1 0 0 0 0 --> 80 1 1 1 1 0 0 0 0 0 0 --> 960

Bitwise operator >> (Right Shift)

<?php
echo 20>>1; //Result 10 echo 193>>1; //Result 96
?>
0 0 0 1 0 1 0 0 --> 20 1 1 0 0 0 0 0 1 --> 193
Result 0 0 0 1 0 1 0 --> 10 1 1 0 0 0 0 0 --> 96

<?php
echo 10>>3; //Result 1 echo 240>>2; //Result 60
?>

0 0 0 0 1 0 1 0 --> 10 1 1 1 1 0 0 0 0 --> 240

Result 0 0 0 0 1 --> 1 1 1 1 1 0 0 -->60

7. String Operators : There are two string operators. The first is the
concatenation operator ('.'), which returns the concatenation
of its right and left arguments. The second is the
concatenating assignment operator ('.='), which appends the
argument on the right side to the argument on the left side.
<?php
$firstName="iBirds";
$lastName="College";
$fullName = $firstName." ".$lastName;
echo $fullName; //Result iBirds College
?>

<?php
$a = "Hello ";
$b = $a . "World!"; // now $b contains "Hello World!"
echo $b;
$a = "Hello ";

Page 17 / 86
$a .= "World!"; // now $a contains "Hello World!"
echo "<br/>$a";
?>

2) Unary Operator (++ --) : PHP offers two unusual and unique operators ++  and --
called  increment and decrement operator respectively.
The use of these two operators will results in the value
of the variable being incremented or decremented by
unity. $i= $i+1 can be written as $i++ and $j= $j-1 can
be written as $--. The operators can be place either
before or after the operand. If the operator is placed
before the variable (++$I or --$I) it is known as pre
incrementing or pre decrementing. If the operator is
placed after the variable ($I++ or $I--) it is known as
post incrementing or post decrementing.
1. Increment Operator : ++
i. Pre Increment : ++$a
ii. Post Increment : $a++
2. Decrement Operator : --
i. Pre Decrement : --$a
ii. Post Decrement : $a--

<?php <?php
$a = 100; $a = 100;
++$a; $a++;
echo $a; //output will be 101 echo $a; //output will be 101
?> ?>
<?php <?php
$a = 100; $a = 100;
echo ++$a; //output will be 101 echo $a++; //output will be 100
echo $a; //output will be 101 echo $a; //output will be 101
?> ?>

Pre incrementing or pre decrementing or post incrementing or post decrementing have


different effect when used in expression. In the pre increment or pre decrement first the
value of operand is incremented or decremented then it is assigned.
Example:
$x=100;
$y=++$x;
Page 18 / 86
After the execution, the value of $y will be 101 and the value of $x will be 101.
In the post increment or post decrement first the value of operand is assigned to the
concern variable and then the increment or decrement perform.
Example:
$x=100;
$Y=$x++;
echo $x."<br/>".$Y.;
After the execution, the value of $Y will be 100 and the value of $x will be 101.

<?php
$a = 10;
$b = 20;
$c = ++$a;
$a = $b--;
$b = $c++;
echo --$a."<br/>"; // output will be ???
echo ++$b."<br/>"; // output will be ???
echo $c--."<br/>"; // output will be ???
echo $a."<br/>"; // output will be ???
echo $b."<br/>"; // output will be ???
echo $c; // output will be ???
?>

3) Ternary Operator ( ? : ) : A ternary operator is an operator that takes three


arguments. The arguments and result can be of different
types. It provides a way to shorten a simple if -- else --
block.

Syntax : condition ? [Statement (if condition is true)] : [Statement (if condition


is false)];

Example:
<?php
$a = 100; $b = 200;
echo $a > $b ? "A is maximum number" : "B is maximum number";
?>

1) Write a program to check whether number is odd or even.


2) Write a program to check whether 2 integer numbers are same or not.
3) Write a program to check whether number is 3 digit or not.
Page 19 / 86
4) Write a program to check whether first integer is completely divisible by second integer.
5) Write a program to Display "iBirds College" if number is single digit.
6) Write a program to check that a number is completely divisible by either 2 or 3.
7) Write a program to check that the number is 4 digit Even integer.
Nested Ternary:

<?php
$a=10; $b=2000; $c=300;
echo $a>$b?($a>$c?"A is Max":"C is max"):($b>$c?"B is maximum
number":"C is Max");
?>
Q) WAP to check whether number is completely divisible by either 2 and 3.

Control Statements
1) Conditional Statements
a) if statement
b) if...else statement
c) if...elseif....else statement
d) switch statement

2) Iterative Statements (Loops)


a) Pre-tested (Entry Control Loops)
i) while Loop
ii) for Loop
iii) foreach Loop
b) Post-tested (Exit Control Loop)
i) do…..while

3) Jumping Statements
a) continue;
b) break;

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.
Page 20 / 86
 if...elseif....else statement - executes one of several blocks of code to be executed.
 switch statement - selects one of many blocks of code to be executed.
Syntax:
If(<Expression>){
[Statement;]
}

Example:
<?php
$num=10;
if ($num>0){
echo "Number is positive : $num";
}

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 (<expression>){
   [Statement;]
  }
else{
   [Statement;]
  }

Example
<?php
$num=0;
if ($num>0){
echo "Number is positive : ".$num;
}
else{
  echo "Number is negative : ".$num;
  }
?>

Q) WAP for even and odd number.


Q) WAP to find leap year.
Page 21 / 86
PHP - The if...elseif....else Statement
Use the if....elseif...else statement to select one of several blocks of code to be executed.
Syntax
if (<expression>){
   [Statement;]
  }
elseif (<expression>){
   [Statement;]
  }
else{
   [Statement;]
  }
Example
<?php
$num=-10;
if($num>0){
echo "Number is positive: $num";
}
else if($num<0){
echo "Number is negative : $num";
}
else{
echo "Number is Zero : $num";
}

Q) WAP to find maximum number from three numbers


<?php
$n1 = 100; $n2 = 50; $n3 = 20;
if($n1>$n2 && $n1>$n3){
echo "First number is maximum : $n1";
}
elseif($n2>$n1 && $n2>$n3){
echo "Second number is maximum : $n2";
}
elseif($n3>$n1 && $n3>$n2){
echo "Third number is maximum : $n3";
}
Page 22 / 86
else{
echo "Equal Numbers";
}?>
1) WAP to check whether is odd and even.
2) WAP to check that 2 numbers are same or not.
3) WAP to checkthe number is 3 digit or not.
4) WAP to check that first integer is completely divisible by second integer.
5) WAP todisplay "iBirds College" if it is a single digit number.
6) WAP to check that the number is 4 digit Even integer.
7) WAP tocheck that the number is completely divisible by 2 and 3.
8) WAP to check whether the number is 2 digit. If it is 2 digit then display sum of digits, otherwise
display entered integer.
9) WAP to check (with 3 numbers) whether the first integer is greater than others or equal to other
integers.
10) WAP to check whether the character is uppercase or lowercase vowel using if.
11) WAP to check whether 2 numbers are different if both are different interchange their value.
12) WAP todisplay maximum, minimum and middle number from 3 integer numbers.
13) WAP to find the area of rectangle.
14) WAP to find the area of Circle.
15) WAP to swapping 2 numbers using 3rd variable.
16) WAP to swapping 2 numbers without using of 3rd variable.
17) WAP to take a number from user and print square of number.
18) WAP to take a number from user and print quabe of number.
19) WAP to take a 4digit number from user and interchange 1st and last digit.
Ex. Num=1347 change 7341
20) WAP to display count of even digits in 4 digit integer number.
21) WAP to check whether a character is an upper caseor lowercase alphabet.
22) WAP to check whether a character is an uppercase vowel or lowercase vowel.
23) WAP to sum of 4 subjects marks and calculate the Percentage of student and find the result.
60>=1st Division
60<&& 50>= 2nd Division
50<&& 40>=3rd Division
40<=fail.
24) Calculate bonus of employees according to salary and print basic salary, bonus and net salary.
1. Salary>=15000 bonus=10%;
2. Salary<15000 && salary >=10000 bonus=8%;
3. Salary <10000 bonus=0%;

Nested if.................

if(<expression>){ else{
if(<expression>){ if(<expression>){
Page 23 / 86
[Statement;] [Statement;]
} }
else{ else{
[Statement;] [Statement;]
} }
} }

Q) WAP to find maximum number from 3 numbers using nested if

<?php
$n1=50; $n2=30; $n3=10;
if($n1>$n2){
if($n1>$n3){
echo "First number is maximum : $n1";
}
else{
echo "Third number is maximum : $n3";
}
}
else{
if($n2>$n3){
echo "Second number is maximum : $n2";
}
else{
echo "Third number is maximum : $n3";
}
}
?>

switch Statement
switch statement is used to select one of many blocks of code to be executed.

Syntax
switch (expression){
case value1:
   [Statement;]
[break;]
case value2:
   [Statement;]
[break;]
Page 24 / 86
default:
[Statement;]
}

Example:
<?php
$day = 1;
switch($day){
case 1:
echo "Monday";
break;
case 2:
echo "Tuesday";
break;
case 3:
echo "Wednesday";
break;
case 4:
echo "Thursday";
break;
case 5:
echo "Friday";
break;
case 6:
echo "Saturday";
break;
case 7:
echo "Sunday";
break;
default:
echo "Invalid Day";
}
?>

Q) WAP to display message as per below condition:


if $day = Monday or Tuesday or Wednesday or Thursday or Friday --> Working Day
if $day = Saturday or Sunday --> Holiday otherwise --> Invalid Day

Page 25 / 86
Q) WAP to check whether given character is a upper case vowel, lower case vowel or
consonant.

Q) WAP to check whether given number is even or odd.

Q) WAP to find number of days in any year


Difference between switch and if

If switch
Multiple expressions are allowed Only single expression can be entered
after case
Duplicate expression can be checked No duplicate case or expression
multiple time
Operators can be used Operators are not allowed after case
if….else order cannot be changed case & default sequence can be
changed

Iterative Statements (Loops)


Loops are used to execute a block of code a specified number of times.

1) Pre-tested (Entry Control Loop)


a. while
b. for
c. foreach

2) Post-tested (Exit Control Loop)


a. do…….while

The PHP while Loop


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

Syntax

Page 26 / 86
while (Expression)
{
  [Statement;]
[continue;]
[break;]
[program counter;]
}

<Expression> --> We can enter:


1) Boolean expression
2) arithmetic expression which will return an integer number
3) 1-true, 0-false 4) constant true or false.
The example below first sets a variable $num to 1 ($num=1;). Then, the while loop will
continue to run as long as $num is less than 6. $num will increase by 1 each time the loop
runs (++$num;):
Example
$num=1;
while($num<6){
  echo " $num<br>";
  ++$num;
}
Q) WAP to print series from 10 to 6 with dry run.
Q) Write a program (with dry run) to find count of digits of an integer number.
Q) Write a program (with dry run) to find sum of digits of an integer number.
Q) Write a program (with dry run) to find reverse of digits of an integer number.

Ans) Program to find count of digits of an integer number.

$num = 7314; $count = 0;


while($num>0){
++$count;
$num = intval($num/10);
}
echo "Count of digit is : $count";
Ans) Program to print sum of digits of an integer number.
<?php
$num = 7314; $sum = 0;
while($num>0){
$sum+= $num%10;

Page 27 / 86
$num = intval($num/10);
}
echo "Sum of digit is : $sum";
?>
Ans) Program to print reverse of digits of an integer number.
$num = 5829; $tmp = 0; $rev = 0;
while($num>0){
$tmp= $num%10;
$rev= ($rev * 10) + $tmp;
$num = intval($num/10);
}
echo "Reverse of digit is : $rev";
?>
Q) WAP to find that given number is a prime number or not
Q) Find the output for below program with dry run

<?php
$x = 2;
$z = 0;
while($z <3){
switch ($z){
case $x:
echo ("0 ");
case $x-1:
echo ("1 ");
case $x-2:
echo ("2 ");
}
$z++;
}
?>
Q)Find the output with dry run
$num = 1;
while($num <= 10){
echo ++num;
}

Jumping Statements
a) continue;
b) break;
Page 28 / 86
continue
The continue statement breaks one iteration (in the loop), if a specified condition
occurs, and continues with the next iteration in the loop.

<?php
$num = 1;
while($num<=6){
if($num==2 || $num==4){
++$num;
continue;
}
echo $num++."<br/>";
}
?>

break

The break statement breaks the loop and continues executing the code after the loop
(if any):

<?php
$num = 1;
while($num<=6){
if($num==4)
{
break;
}
echo $num++."<br/>";
}

?>

Page 29 / 86
Q) WAP to find that the number is prime number or not.

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{
  [Statement;]
[continue;]
[break;]
[program counter;]
}while(Expression);

The example below first sets a variable $x to 1 ($x=1;). Then, the do while loop will write
some output, and then increment the variable $x with 1. Then the condition is checked (is
$x less than, or equal to 5?), and the loop will continue to run as long as $x is less than, or
equal to 5:

Example
<?php
$x=1;
do
{
  echo "The number is: ".$x++."<br>";
  }while ($x<=5);
?>
$x o.p. $x<=5
Page 30 / 86
---- ---- ---------
1 1 2<=5 - T
2
Q)Find output for below program with dry run
$num=11;
do{
echo "<br/>". --$num;
}while($num > 1);

Q) WAP (with dry run) to find count of digits of an integer number using do..while loop.
Q) WAP (with dry run) to find sum of digits of an integer number using do..while loop.
Q) WAP (with dry run) to find reverse of digits of an integer number using do..while loop.
Q) WAP to find that given number is a prime number or not using do....while loop.

The PHP for Loop


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

Syntax
Step (1) Step (2) Step (4)
for ([initialization]; [expression]; [increment/decrement counter]){
   [statement;]
Step (3) [continue;]
[break;]
}

Parameters:
 init counter : It initializes the loop counter value. This part of loop will execute
first and pointer will not come here again.
 expression : Evaluated for each loop iteration. If it evaluates to TRUE, the
loop continues. If it evaluates to FALSE, the loop ends.
 increment counter:Increases or decreases the loop counter value

The example below displays the numbers from 1 to 5:

Examples
Page 31 / 86
<?php
$x=1;
<?php for (;;){
for ($x=1; $x<=5; $x++){ if($x==6){
echo "The number is: $x break;
<br>"; }
}   echo "The number is: $x <br>";
?> $x++;
}
?>

Examples

<?php <?php
for($i=1, $j=10; $i<=5, $j>=8; $i++, for($i=1, $j=10; $i<=5 || $j<=3; $i++,
$j--){ $j--){
echo "I is : ".$i." and J is : ". echo "I is => ".$i." and J is => ".
$j."<br/>"; $j."<br/>";
} }
?> ?>

Loop

1 2 1 A 1 1
23 46 35 AB 10 12
456 8 10 12 7 9 11 ABC 101 121
78910 14 16 18 20 13 15 17 19 ABCD 1010 1212

1) Print odd numbers from 1 to 50.


2) Put starting and ending number and print even numbers from that series.
3) Put 5 integers and display maximum number from that.
4) Put 10 integers and display count of even integers and sum of odd integers.
5) Put 5 integers and display count of 3 digit even integers.
6) WAP to display average of digits from a number.
7) WAP to display average of even digits in a number.
Page 32 / 86
8) Put 10 integersand print count of positive and negative integers and zero
9) WAP to check whether a number is prime use of break statement.
10) WAP to display factorial of a number.
11) WAP to check whether the number isperfect number or not.
Ex. Num=28 1+2+4+7+14=28
12) WAP to check whether the number is Armstrong or not.
Ex. Num=153 (1*1*1) + (5*5*5) + (3*3*3) =153
13) WAP to check whether the number isPalindrome or not.
Ex. Num=121 25852
14) WAP to print only prime numbers from 1 to 1000.
15) WAP to print table inbelow format.
Ex. Number=5
5 *1=5 5 *2=10 5 *3=15 .................. 5 *10=50

Nesting of Loop(Structure of nested loops)


Loop 1 parent loop
{
Loop 2  child loop
{
[Statements;]
[break;]
[continue;]
}
Loop 3  parent & child loop
{
Loop 4 child loop
{
[Statements;]
[break;]
[continue;]
}
}

Example:
**** <?php
**** for($row=1; $row<=4; $row++){
**** for($col=1; $col<=4; $col++){
Page 33 / 86
**** echo "*";
}
echo "<br/>";
}
?>

Example
* <?php
** for($row=1; $row<=4; $row++){
*** for($col=1; $col<=$row; $col++){
**** echo "*";
}
echo "<br/>";
}
?>
Example <?php
___* echo "<table>";
__** for($row=1; $row<=4; $row++){
_*** echo "<tr>";
**** for($s=3; $s>=$row; --$s){
echo "<td>_</td>";
}
for($col=1; $col<=$row; $col++){
echo "<td>*</td>";
}
echo "</tr>";
}
echo "</table>";
?>

Make the dry run of below programs


<?php <?php
for($row=1; $row<=4; $row++){ for($row=1; $row<=4; $row++){
for($col=1; $col<=$row; $col+ for($col=1;
+){ $col<=$row; $col++){
echo $row; echo $col;
} }
echo "<br/>"; echo "<br/>";
} }
?> ?>
Page 34 / 86
Write code for below programs with dry run.

1 2 1 A 1 1
23 46 35 AB 10 12
456 8 10 12 7 9 11 ABC 101 121
78910 14 16 18 13 15 17 19 ABCD 1010 1212
20
1              1       * *
54 3 2 1 1010 12          21 *****     *** **
54 3 2 101 123      321 *      *   ***** ***
54 3 10 1234  4321 *      * ******* ****
54 1 123454321 *      *   ***** *****
5 ***** ****
    ***
***
      * **
*

*      * A A 1 12345 1
  *  *  **  ** AB BA 2 6 678 121
    *    *  *  * ABC CBA 3 7 10 9 1248421
  *  *  *      * ABCD DCBA 4 8 11 13 10 11 12 1 2 4 8 16 8 4
*      * *      * ABCDE EDCBA 5 9 12 14 13 14 15 16 21
ABCDEFEDCB 15 17 1248421
A 121
Page 35 / 86
1

Array
An array is a special variable, which can hold more than one value at a time under a
single name.Values are stored in contiguous memory locations. In PHP arrays are
collection of non-homogeneous of data. We can create dynamic arrays in PHP.

There are two types of arrays:


1) Indexed ArrayArrays with numeric index
a. Single Dimension Array
b. Double Dimension Array

2) Associative ArrayArrays with named keys


a. Single Dimension Array
b. Double Dimension Array
Single Dimensional Indexed Array
A single dimensional array can hold many values under a single name, and you can
access the values by referring an index number.

$arr 0 1 2
Syntax: 10 20 30
Declaration $arrayName = array();
Example $arr = array();

Initialization $arrayName[Index No.] = value;


Example $arr[0]=10; $arr[1] = 20; $arr[2]=30;

Declaration & initialization Syntax


$arrayName = array(value1, value2,.....ValueN);
Example $arr = array(10,20,30);

Printing array elements


echo $arr[0]."<br>";
echo $arr[11."<br>";
echo $arr[2]."<br>";

Printing array elements using loop


<?php
$arr = array(10, 20, 30);
for($i=0; $i<3; $i++){

Page 36 / 86
echo $arr[$i]."<br>";
}
?>
Printing array elements with loop using count function
<?php
$arr = array(10, 20, 30, 40, 50);
for($i = 0; $i<count($arr); $i++){
echo $arr[$i]."<br/>";
}
?>
Printing array elements using foreach loop
$arr = array(10, 20, 30, 40, 50, 60, 70);
foreach($arr as $abc){
echo $abc."<br/>";
}
Adding value at last index of array
Syntax
$array_name[]=value;

Example
$marks[0]=20; $marks[1]=50; $marks[2]=40; $marks[]=30; //it will take 30 on 3 index

Arrays are non-homogeneous in PHP


$arr = array(10, 20);
$arr[] = 60;
$arr[] = "iBirds";
$arr[] = 31.25;
$arr[] = true;
var_dump($arr);

Output
array(size=6)
0 =>int10
1 =>int20
2 =>int60
3 =>string'iBirds'(length=6)
4 =>float31.25
5 =>booleantrue
Page 37 / 86
Q) WAP to print sum of array elements
<?php
$arr = array(10, 20, 30, 40); $sum=0;
for($i=0; $i<count($arr); ++$i){
$sum+=$arr[$i];
}
echo "Sum of array elements is : $sum";
?>

Assignment
1) WAP to print sum of even and odd numbers in array.
2) WAP to print maximum number of array.
3) WAP to find prime numbers in array and store prime in new array.
4) WAP to sort the array elements.
5) WAP to take two arrays and create new array of sum of that array.
6) WAP to create new array of 5 elements array with sum of first and last position.
Example: newArr[0]=arr[0]+arr[9], newArr[1]=arr[1]+arr[8], newArr[2]=arr[2]+arr[7].
7) WAP to create array of even numbers from an array
8) WAP to display first prime integer in 5 elements array.
9) WAP to display count of prime numbers and display it.
10) WAP to replace all prime integers with their sum of digits.
11) Count of vowels in string.
12) Count Uppercase Alphabets in string.

Two – Dimensional Indexed Array

$marks 0 1 2
0 1 2 3
1 4 5 6
2 7 8 9

Page 38 / 86
An array can also contain another array as a value. In such a way we can create multi-
dimensional arrays:
1) Collection of rows & columns
2) Each element can be accessed by its row and column index number.

Syntax (1):
Declaration: $arrayName=array();

Initialization: $arrayName [row –index][col –index] = value;

Example:
Declaration: $marks = array();

Initialization:
$marks[0][0]=1;
$marks[0][1]=2;
$marks[0][2]=3;
$marks[1][0]=4;
$marks[1][1]=5;
$marks[1][2]=6;
$marks[2][0]=7;
$marks[2][1]=8;
$marks[2][2]=9;

Accessing 2 D array

Syntax: $arrayName[row index][col index];

Examples:
echo $marks[0][0]."<br/>"; //output 1
echo $marks[0][1]."<br/>"; //output 2
Page 39 / 86
echo $marks[0][2]."<br/>"; //output 3
echo $marks[1][0]."<br/>"; //output 4
echo $marks[1][1]."<br/>"; //output 5
echo $marks[1][2]."<br/>"; //output 6
echo $marks[2][0]."<br/>"; //output 7
echo $marks[2][1]."<br/>"; //output 8
echo $marks[2][2]; //output 9

Syntax (2):We can pass single dimension array to two dimension array as value.
Example:
$a1 = array(10, 20, 30);
$a2 = array(40, 50, 60);
$a3 = array(70, 80, 90);
$marks = array($a1, $a2, $a3);
Syntax (3):
$marks = array(array(100, 200, 300), array(400, 500, 600), array(700, 800, 900));
Printing 2D Array elements through loops:
for($i=0; $i<=2; $i++){
for($j=0; $j<=2; $j++){
echo $marks[$i][$j]. "&nbsp;";
}
echo "<br>";
}
Dry Run
$i $i<=2 $j $j<=2 $marks[$i][$j] Output
0 0<=2 T 0 0<=2 T $marks[0][0] 100200 300
1 1<=2 T $marks[0][1]
2 2<=2 T $marks[0][2]
3 3<=2 F
1 1<=2 T 0 0<=2 T $marks[1][0] 400 500 600
1 1<=2 T $marks[1][1]
2 2<=2 T $marks[1][2]
3 3<=2 F
2 2<=2 T 0 0<=2 T $marks[2][0] 700 800 900
1 1<=2 T $marks[2][1]
2 2<=2 T $marks[2][2]
3 3<=2 F
3 3<=2 F
Q) WAP to print sum of 2D array elements
<?php
Page 40 / 86
$arr = array(array(1, 2, 3), array(4, 5, 6), array(7, 8, 9)); $sum=0;
for($row=0; $row<3; $row++){
for($col=0; $col<3; $col++){
$sum+=$arr[$row][$col];
}
}
echo "Sum of array elements is : $sum";
?>
Assignments
1) WAP to print sum of rows & columns of 3*3 matrix
2) WAP for sum of corners of 3*3 matrix
3) WAP for sum of all elements except center element of array
4) WAP for sum of array elements except corners
5) WAP to print sum of diagonal row of 3*3 matrix.

Zig – Zag Array 1 2 3 4


<?php 30 55 0
//Declaration & Initialization Syntax 84 74 94 1
$arr1 = array(30, 55); 11 22 33 44 2
$arr2=array(88, 74, 94); 77 66 3
$arr3=array(11, 22, 33, 44);
$arr4=array(77, 66);
$record=array($arr1, $arr2, $arr3, $arr4);
?>

//Declaration & Initialization Syntax 2


$record = array(array(30, 55), array(88, 74, 94), array(11, 22, 33, 44), array(77, 66));

//Printing Jagged Array with loops


for($i=0; $i<count($record); $i++){
for($j=0; $j<count($record[$i]); $j++){
echo $record[$i][$j]."&nbsp;";
}
echo "<br/>";
}
?>

count($record) : It will return number of rows in array.

count($record[$i]) : It will return number of columns in specified row.

Page 41 / 86
Associative Array
Associative array is a collection of key and value. Each element can be accessed by
using key. Key can be alphanumeric character and key can’t be duplicated. Two things
create an associative array 1) Key 2) Value.

$student
Arun 9784111111
Rohit 7524222222
Vivek 9214333333

Declaration:
Syntax: $array_name=array();

Initialization: $array_name['Key']="Value";

Example:
$Student=array();
$Student['Arun']=9784111111;
$Student ['Rohit']=7524222222;
$Student ['Vivek']=9214333333;
Declaration & Initialization of an associative array:
Syntax:
$arrayName=array('key1'=>value1,'key2'=>value2,'key3'=>value3);
Example:
$Student=array("Arun"=>9784112233,"Rohit"=>9828112233, "Vivek"=>9242112233);
Printing:
echo $Student['Amit']."<br/>";
echo $Student['Rohit']."<br/>";
echo $Student['Vivek']."<br/>";

$Student=array("Arun"=>1111, "Rohit"=>2222, "Priya"=>3333, "Vipin"=>4444,


"Raj"=>5555);

foreach($Student as $key=>$value){
echo $key." = ".$value."<br/>";
}

Q) WAP to print 2, 5, 6, 9, 11, 14 index numbers values.

Page 42 / 86
2 Dimensional Associative array
$student
Contact Course Timing
Gaurav 9414 HTML 09am
Vinit 9897 Java 10 am
Sandeep 8223 PHP 11am

$student = array();
Declaration & Initialization (Syntax 1):
$S1=array("Contact"=>9414, "Course"=>'HTML', "Timing"=>'09 am');
$S2=array("Contact"=>9897, "Course"=>'Java', "Timing"=>'10 am');
$S3=array("Contact"=>8223, "Course"=>'PHP', "Timing"=>'11 am');

$student['Gaurav']=$S1;
$student['Vinit']=$S2;
$student['Sandeep']=$S3;
Declaration & Initialization (Syntax 2):
$student['Gaurav']=array("Contact"=>9414, "Course"=>'HTML', "Timing"=>'09 am');
$student['Vinit']=array("Contact"=>9897, "Course"=>'Java', "Timing"=>'10 am');
$student['Sandeep']=array("Contact"=>8223, "Course"=>'PHP', "Timing"=>'11 am');

Printing 2D Associative Array with foreach loop


foreach($student as $key1=>$value1){
echo "Student's Name is = ".$key1."<br/>";
foreach($value1 as $key2=>$value2){
echo "&nbsp;&nbsp".$key2." = ".$value2."<br/>";
}
echo "<br/>";
}

Output
Student's Name : Gaurav
Contact : 9414
Course : HTML
Timing : 09 am

Student's Name : Vinit


Contact : 9897
Course : Java
Page 43 / 86
Timing : 10 am

Student's Name : Sandeep


Contact : 8223
Course : PHP
Timing : 11 am

Q) Print 2D associative array as per below format

Contact Course Timing


Gaurav 9414111111 HTML 09am
Vinit 9214222222 Java 10 am
Sandeep 9829000000 PHP 11am

Functions:
1) A function is a block of statements that can be used repeatedly in a program.
2) Writing function avoids rewriting the same code over and over.
3) It reduces program size and provides facility to manage and debug the code.
4) A function will not execute immediately when a page loads.
5) A function will be executed by a call of user. Users have to call it by its name and
arguments.
6) Function may return a value.
7) Function can return only one value at a time using return keyword.
8) Function uses return keyword to return a value or terminate a function.
9) function keyword is used to define a function.
10) We can pass variable to function by value or by reference.
11) Function name is not case sensitive in PHP.

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 separate them with a comma.

There are two types of functions in PHP.


1) User Defined Functions
a. No accept argument and no return value
b. Accept argument but no return value
Page 44 / 86
c. No accept argument but return value
d. Accept argument and return value

2) Library Functions
a. String Functions
b. Date & Time Functions
c. Array Functions

1) User define functions


a) No accept argument and no return value

Syntax:
function FunctionName(){
[Statement;]
}

Calling function:
functionName();

Example:

<?php
function Show(){
echo "Hello iBirds";
}

Show(); //Calling function


?>

Output: Hello iBirds

b) Accept argument but no return value


Page 45 / 86
Syntax for passing argument in function:

function FunctionName($arg1, $arg2……$argN){


[Statement;]
}
Calling function: functionName($arg1, $arg2……4argN);

Example:
<?php
function ShowMsg($name){
echo "Hello $name";
}

ShowMsg("India");
?>
Output: Hello India
c) No accept argument but return value
Syntax
function FunctionName(){
[Statement;]
return Value;
}

Example
<?php
function basicSalary(){
return 25000;
}
$bs = basicSalary();
echo "Basic Salary is = ".$bs;
?>
Output Basic Salary is = 25000

d) Accept argument and return value


Syntax
function FunctionName($arg1, $arg2……$argN){
[Statement;]
return value;
}

Page 46 / 86
Example
<?php
function getArea($radius){
$area = $radius * $radius * 3.14;
return $area;
}

$area=getArea(10);
echo "Total area is : $area";
?>

Output: Total area is : 314

Default Parameter Function:


Syntax
function function_name($arg1=value1, $arg2=value2……..$argN=valueN){
[Statement;]
[return value;]
}

Example
<?php
function Sum($a=10, $b=20, $c=30){
return($a+$b+$c);
}

echo Sum(); //Output 60


echo Sum(1); //Output 51
echo Sum(1, 2); //Output 33
echo Sum(1, 2, 3); //Output 6
?>

Passing array as argument in function


syntax
function functionName($arrayName){
[statement;]
}

Page 47 / 86
Example
<?
function printArray($arr){
foreach($arr as $value){
echo $value."<br/>";
}
}
$students = array("Sunil", "Himanshu", "Deepak", "Priyanka", "Aditi", "Dilip");
$marks = array(58, 92, 76, 99, 69, 44, 55, 66);
$contact = array(9414, 9829, 9424);
printArray($students); echo "<hr/>";
printArray($marks); echo "<hr/>";
printArray($contact);
?>

Passing array as argument and returning array from function


<?php
function getEven($arr){
foreach($arr as $value){
if($value%2==0) $result[]=$value;
}
return $result;
}
$a = array(5, 6, 3, 7, 8, 12, 15, 18);
$data = getEven($a);
foreach($data as $value){
echo "$value<br/>";
}
?>

1) WAP which accept a number and print table of that number


2) WAP which accept a number and print factorial of that number

<?php
//Pass a variable to a function by value.
function value($num){
$num++;
echo $num."<br/>";
}
$a = 10;
Page 48 / 86
value($a)."<br/>";
echo $a;
"<br/><br/>";

//You can pass a variable to a function by reference.


function changeValue(&$var)
{
$var++;
}

$result=5;
echo $result."<br/>";
changeValue($result);
echo $result; // $result is 6 here
?>
We can return more than one value from function.
<?php
//Returning more than one value from function
function netSalary($bs, &$ta, &$da, &$hra, &$ns){
$ta=($bs*10/100);
$da=($bs*50/100);
$hra=($bs*5/100);
$ns=$bs+$ta+$da+$hra;
}

$basicSalary=5000; $ta=0; $da=0; $hra=0; $netSalary=0;


netSalary($basicSalary, $ta, $da, $hra, $netSalary);
echo "Basic Salary is : $basicSalary<br/>";
echo "TA is : $ta<br/>";
echo "DA is : $da<br/>";
echo "HRA is : $hra<br/>";
echo "Net Salary is : $netSalary";
?>

Recursive functions
Sometimes the easiest way to model a problem is to make a function call itself - a
technique known as recursive function calling.
<?php
function rec($num){
if($num==21) return;

Page 49 / 86
echo $num++."<br/>";
rec($num);
}

rec(1);
?>

Find factorial using function recursion


<?php
function factorial($number) {
if ($number < 2) return 1;
else return ($number * factorial($number-1));
}
echo factorial(5);
?>
PHP Library Functions
String Functions

Here Doc Operator For String And Methods


<<< Heredoc Operator: used for storing long string.
<?php

$msg=<<<abc
Hello All 'We lcome' to "iBirds" and See Its a "String",
<br> 'Single' and "Double";
Shastri Nagar,
Ajmer
abc;
echo $msg;
//exit;
//die("Bye");
?>

strlen(String): It returns the length of string


<?php
$msg = "iBirds College";
echo strlen($msg);
?>

substr(msg) : it returns number of character from string (: Returns a substring)

Page 50 / 86
Syntax:
substr(string, start_from[, number_of_characters])
<?
$msg="This is example";
echo substr($msg,6); //it will return string from 6 position i.e. s example
echo substr($msg,8,4); //it will return 4 characters from 8 position i.e. exam
?>

strtoupper(string)
<?
$msg = "hello india";
echo strtoupper($msg);
?>

strtolower(string)
<?
$msg = "HELLO INDIA";
echo strtolower($msg);
?>

ucfirst(string) : first letter upper case


<?
$msg = "hello world"; //Hello world
echo ucfirst($msg);
?>

ucwords(string) : first letter of all words upper case


<?
$msg = "hello world hello india<br>"; //Hello World Hello India
echo ucwords($msg);
$msg = "hello woRLd hElLO iNDIa";
echo ucwords(strtolower($msg));
?>

strrev() : Reverses a string

<?php
echo strrev("Hello World!");
Page 51 / 86
?>

str_repeat(string,timesOfRepeat)

<?
$msg = "Welcome to iBirds<br>";
echo str_repeat($msg,10);
?>

str_replace(CharacterToBeReplaced, NewCharacter, string)


<?php
//$msg = "iBird Education";
echo str_replace("i","a",$msg);
?>

ltrim(string), rtrim(String), trim(String)

<?php
$str=" iBirds";
echo "ABC".ltrim($str);
?>

<?php
$str="iBirds ";
echo rtrim($str)."ABC";
?>

<?php
$str=" iBirds ";
echo "ABC".trim($str)."XYZ";
?>

Page 52 / 86
Array Functions

implode(saperator, array): Converts an array into String

<?php
$marks = array(3,4,4,5);
var_dump($marks);
$strMarks = implode(",",$marks);
echo "<br/>" . $strMarks . "<br/>";
echo "<br/>";
?>

explode(saperator, String) --> It converts a string into array

<?php
$msg = "Ajmer,Jaipur,Kota,Bikaner, 90";
echo $msg;
$cities = explode(",",$msg);
echo $cities;
//Debugging Tools
//print_r($cities); it will display array value with index number
//var_dump($cities); it will print arrary value with index number and data type
foreach($cities as $value)
{
echo $value."<br/>";
}
?>
Page 53 / 86
<?php
//count(array) --> it returns size of array
$arr=array("Name"=>"Raj", "Age"=>15, "Marks"=>88.75, "Is_Married"=>true);
echo "Length of Array is => ".count($arr);
echo "<br/>";
foreach($arr as $key=>$value)
{
echo $key." = ".$value."<br/>";
}
echo "<br/>";
?>

sort() - sort arrays in ascending order


<?php
//sort(array) ==> it sorts the array elements
//$marks = array(9,14,4,55,22,11);
$marks = array("Mahendra", "Gaurav", "Akash", "Saroj", "Shipra", "Bhawna",
"Priya", "Raveena", "Aman");
sort($marks);
foreach($marks as $values)
{
echo $values."<br/>";
}
echo "<br/>";
echo "<br/>";
?>

rsort() - sort arrays in descending order

<?php
//$marks = array(9,14,4,55,22,11);
$marks = array("Mahendra", "Gaurav", "Saroj", "Shipra", "Priya", "Raveena");
rsort($marks);
foreach($marks as $values)
{
echo $values."<br/>";
}
echo "<br/>";
echo "<br/>";
Page 54 / 86
?>

asort() - sorts associative array in ascending order, according to the value

<?php
$age = array("Peter"=>35, "Joe"=>43, "Ben"=>37, "AAA"=>12, "BBB"=>20,
"CCC"=>5);
asort($age);
foreach($age as $key=>$value)
{
echo $key." = ".$value."<br/>";
}
?>

arsort() - sorts associative array in descending order, according to the value


<?php
$age = array("Peter"=>"35", "Joe"=>"43", "Ben"=>"37", "CCC"=>"12",
"BBB"=>"20", "AAA"=>"5" );
arsort($age);
foreach($age as $key=>$value)
{
echo $key." = ".$value."<br/>";
}
?>

ksort() - sorts associative array in ascending order, according to the key

<?php
$age = array("Prakash"=>"35", "Javed"=>"43", "Badri"=>"37", "Rohan"=>"12",
"Aman"=>"20", "Waseem"=>"5" );
ksort($age);
foreach($age as $key=>$value)
{
echo $key." = ".$value."<br/>";
}
?>

krsort() - sorts associative arrays in descending order, according to the key

Page 55 / 86
<?php
$age = array("Devendra"=>"35", "Aarti"=>"43", "Vinod"=>"37",
"Kapil"=>"12", "Shipra"=>"20", "Raveena"=>"5" );
krsort($age);
foreach($age as $key=>$value)
{
echo $key." = ".$value."<br/>";
}
?>

is_array(array): Returns true (1) if argument is an array otherwise false (no value)

<?php
$arr=10;
//$arr = array(4,5,6,7);
echo is_array($arr) ? 'This is an Array' : 'This is not an Array';
?>

array_key_exists ==> Returns true (1) if finds key in an associative array otherwise false
(no value).

<?php
$marks = array("hindi" => 36, "english" => 34, "maths" => 67);
echo array_key_exists("Hindi",$marks)? 'Key Found' : 'Key not found';
?>

array_keys(array): Returns keys (create single dimension index array of keys) of an


associative array

<?php
$marks = array("hindi" => 36, "english" => 34, "maths" => 67);
$keys = array_keys($marks);
var_dump($keys);
?>
array_values(array): Returns values of an associative array

Page 56 / 86
<?
$marks = array("hindi" => 36, "english" => 34, "maths" => 67);
$values = array_values($marks);
var_dump($values);
?>

isset($argument): It returns true if found value (in variable or array) otherwise false.

<?php
$a=1;
echo isset($a)?"Value is there":"variable is empty";

$marks = array("hindi" => 36, "english" => 34, "maths" => 67);
//var_dump($marks);

$res = isset($marks["hindi"]);
echo "<br/>";
var_dump($res);
echo "<br/>";
$res = isset($marks["Hindi"]);
var_dump($res);
echo "<br/>";
$res = isset($msg);
var_dump($res);
echo "<br/>";
$res = isset($msg_var);
var_dump($res);
echo "<br/>";
?>
in_array($argument): It returns true (1) if found value (in index array) otherwise
false.<br/>

<?
$arr =array("ajmer","kota","jaipur");
echo in_array("jaipur",$arr);
?>
Date & Time Functions
<?php
echo date("d-m-Y")."<br/>"; //31-07-2015
echo date("d-M-y")."<br/>"; //31-Jul-15
echo date("D d-M-y")."<br/>"; //Fri 31-Jul-15
Page 57 / 86
echo date("D d-M-Y")."<br/>"; //Fri 31-Jul-2015

//Change default Time Zone


//date_default_timezone_set("Asia/Calcutta");

date_default_timezone_set('America/Los_Angeles');

$scr = date_default_timezone_get();
echo $scr;
echo "<br/><br/>";
?>
<?php
//Date and Time
echo date("d-m-Y h:i:s") . "<br/>"; //it willl display time as per given time zone
//Date and Time with am/pm
echo date("d-m-Y h:i:s a") . "<br/>";

echo date("M-Y") . "<Br/>";


?>

Form in PHP (Registration.php)


<html>
<head>
<title>Registration Form</title>
</head>

<body>
<form action="process.php" method="get">
<table border="2px" align="center">
<tr>
<th>User Name</th>
<td><input type="text" name="uname"/></td>
</tr>
<tr>
<th>Password</th>
<td><input type="password" name="password"/></td>
</tr>
<tr>
Page 58 / 86
<th>Address</th>
<td><textarea name="address"></textarea></td>
</tr>
<tr>
<th>City</th>
<td>
<select name="city">
<option value="">--- Select City ---</option>
<option value="Ajmer">Ajmer</option>
<option value="Jaipur">Jaipur</option>
<option value="Kota">Kota</option>
<option value="Bikaner">Bikaner</option>
</select>
</td>
</tr>
<tr>
<th>Gender</th>
<td>
<input type="radio" name="gender" value="Male"/>Male
<input type="radio" name="gender" value="Female"/>Female
</td>
</tr>
<tr>
<th>Course</th>
<td>
<select name="course[]" multiple>
<option value="HTML">HTML</option>
<option value="CSS">CSS</option>
<option value="PHP">PHP</option>
<option value="Java">Java</option>
<option value="Salesforce">Salesforce</option>
</select>
</td>
</tr>
<tr>
<th>Hobbies</th>
<td>
<input type="checkbox" name="hobbies[]" value="Singing"/>Singing
<input type="checkbox" name="hobbies[]" value="Reading"/>Reading
<input type="checkbox" name="hobbies[]" value="Surfing"/>Surfing
Page 59 / 86
</td>
</tr>
<tr>
<td><input type="submit" value="Submit Form"/></td>
<td><input type="reset" value="Refresh Form"/></td>
</tr>
</table>
</form>
</body>
</html>

Form in PHP (Process.php)


<?php
error_reporting(0);
//$name = $_GET['uname'];
//$password = $_POST['uname'];
$name = $_REQUEST['uname'];
$password = $_REQUEST['password'];
$address = $_REQUEST['address'];
$city = $_REQUEST['city'];
$gender = $_REQUEST['gender'];
$cr = $_REQUEST['course'];
$course = implode(",",$cr);
$hobbies = implode(",", $_REQUEST['hobbies']);
?>
<table border="2px" align="center">
<tr><th>User Name</th><td><?= $name ?></td></tr>
<tr><th>Password</th><td><?= $password ?></td></tr>
<tr><th>Address</th><td><?= $address ?></td></tr>
Page 60 / 86
<tr><th>City</th><td><?= $city ?></td></tr>
<tr><th>Gender</th><td><?= $gender ?></td></tr>
<tr><th>Course</th><td><?= $course ?></td></tr>
<tr><th>Hobbies</th><td><?= $hobbies ?></td></tr>
<tr>
<td colspan="2" align="right">
<a href="registration.php?nm=<?= $name ?>&add = <?= $address ?>">Edit
Information</a>
</td>
</tr>
</table>

Structured Query Language ( SQL )

Create Database : college


1) Create Table : students
Fields :
sid(int, auto increment, primary key, starts from 1)
fname (varchar 30)
lname (varchar 30)
city (varchar 20)
dob (date)
gender (enum - "Male", "Female")

2) Create Table : course


Fields :
cid (primary key, auto number, Starts from 101)
name (varchar 30)
duration (varchar 10)
fees (int)

Page 61 / 86
status (enum - "Active", "Inactive")

3) Create Table : registration


Fields:
rid (int, auto increment, starts from 501)
sid (int)
cid (int)
rdate (timestamp)
status (enum - "Active", "Inactive")

4) Create Table : fees


Fields :
fid (primary key, auto number)
sid (int)
cid (int)
amount (int)
dod (timestamp)

5) Create Table : faculty


fid (primary key, auto number)
Page 62 / 86
name (varchar 30)
subject (varchar 20) salary(int)

What is SQL?
 SQL stands for Structured Query Language
 SQL lets you access and manipulate databases

What Can SQL do?


 SQL can create new databases
 SQL can create new tables in a database
 SQL can insert records in a database
 SQL can update records in a database
 SQL can delete records from a database
 SQL can execute queries against a database
 SQL can retrieve data from a database

DDL: Data Definition Language


Structure of Database is created, manipulated and deleted
Commands ==> create, alter and drop

DML: Data Manipulation language


Commands ==>Insert, Update, truncate and delete

DCL: Data Control Language

A data control language (DCL) is a syntax similar to a computer programming language


used to control access to data stored in a database. In particular, it is a component of
Structured Query Language (SQL).

What is the difference between SQL and MySQL or SQL Server?

SQL or Structured Query Language is a language; language that communicates with a relational database
thus providing ways of manipulating and creating databases. MySQL and Microsoft’s SQL Server both
are relational database management systems that use SQL as their standard relational database language.

Page 63 / 86
Database Tables
A database most often contains one or more tables. Each table is identified by a name (e.g.
"student" or "faculty"). Tables contain records (rows) with data.

primary key >> unique + not NULL ==> is called constant (means validation of fields
based on SQL)

one table's primary key is used in another table as foreign key


in a table second primary key can be created using UNIQUE + NOT NULL

How can create database


create database <name of database>
create database college
___________________________________

how can create table in database


create table <name of table>(<fields...>)
create table faculty(id int primary key auto_increment, name varchar(20),
ctcnbrvarchar(10))
____________________________________________________

INSERT INTO tablename[(field1, field2,...)] values(value1, value2,...)

insert into students(fname, lname, city, dob, gender) values('Naved', Khan', 'Jaipur', '1991-
06-23', 'Male')

insert into students values(null, 'Deepak','Sharma', 'Ajmer', '1991-04-23', 'Male')

insert into students(fname, lname, city, dob, gender) values('Vikas', 'Jain', 'Ajmer', '1990-
11-10', 'Male'), ('Anita', 'Sharma', 'Kota', '1990-11-10', 'Male'), ('Akshya', 'Kumar', 'Kota',
'1990-11-10', 'Male')

insert into student(fname, email, password) values('Farhan', 'farhan@gmail.com',


des_encrypt('farhankhan'))

select name, email, des_decrypt(password) from student

UPDATE tableName set field1=value, field2=value,... [where expression]


update students set city='Ajmer' where id=3

Page 64 / 86
update students set fname='Priyanka' where id=5
update students set city='Jaipur' where id>5 and id<15
update student set fname='' where id =25
ALTER TABLE `student` ADD `contact` VARCHAR( 10 ) NOT NULL

Removing Records:
delete from TableName [where expression]
delete from students where id = 7

truncate table tableName //it deletes all the records from table and start index with 1
truncate table student // but it will not delete the structure of table

Select -->The SELECT statement is used to select data from a table.

SELECT fieldName1, fieldName2,... FROM <tablename>


[WHERE expr]
[Group By <fieldName>]
[Having <expr>]
[Order By <fieldName> [asc/desc]]
[Limit <recordno>]

SELECT * FROM students


SELECT fname, lname, city from students
select * from students where gender = "female"

select fname, lname, city, gender from students where gender='Female' or city = "ajmer"

Wild Card Characters


_ ->Any Single Character Only Single Length
% -> All Characters Any Number of Length

like
select * from students where fname like "_____"
select * from students where fname like "K____"
select * from students where fname like "%i"
select * from students where fname like "sa%"
select * from students where fname like "%sa%"
select * from students where fname like "%ar%" or gender like "%em%"

Page 65 / 86
Expression Query
select fname, lname, salary, salary * 12 from faculty
select*, salary * 12 from faculty
Alias: Giving a new name to field or table.
select name, dept, salary, salary * 12 as AnnualSalary from faculty
select name, dept, salary, salary * 12 as "AnnualSalary" from faculty
select f.fname, f.lname, f.salary, salary * 12 as 'Annual Salary' from faculty as f
select name, dept, salary, salary/100*10 as HRA from faculty
select name, dept, salary, salary*0.10 as HRA, salary+salary*0.10 as NetSalary from
faculty

SQL Server
select name, salary, salary * 12 as "Annual Salary" from faculty
select name, salary, salary * 12 as "Annual Salary" from faculty where (salary * 12) >
150000

select name, dept, salary, salary*0.10 as HRA, salary+salary*0.10 as NetSalary from


faculty where salary+salary*0.10>10000

Order By
select * from students order by id desc
select * from students order by fname
select * from students order by city, fname
select * from students order by city, fnamedesc
select * from students order by citydesc, fname desc

Limit
select * from students limit 5
select * from students limit 3, 7

Aggregate Queries
Max
Min
Sum
Avg
Count

select sum(amount) as TotalAmount from fees


Page 66 / 86
select max(amount) as MaximumAmount from fees
select max(salary) as MaxumumSalary from faculty
select count(id) as total_records from faculty
select sum(salary) as total_salary from faculty
select avg(salary) as avg_salary from faculty

Functions
1. concat: Concate 2 or more fields
select concat(fname, " - ", city) as Address from students
select concat(id, " => ", fname, "- ", city) as Address from students

2. in
select * from students where id = 301 or id = 305 or id = 309
select * from students where id in(301, 302, 303, 309, 313)
select * from course where name in('Java', 'PHP', 'VB')
select * from course where name not in('Java', 'PHP', 'VB')

3. between
select * from students where id >= 309 and id <= 320
select * from students where id between 309 and 320
select * from student where id not between 9 and 20

4. Day(date)
select * from students where day(dob)=22

5. Month(date)
select* from students where month(dob)=4

6. Year(Date)
select * from students where year(dob)=1999

select dob, day(dob) as Days, month(dob) as Months, year(dob) as Years from students

7. current_date returns systems date


select current_date

8. current_times: returns System's Current Time


Select current_time

select current_timestamp //it will display date and time


Page 67 / 86
9. UPPER(), LOWER(), NOW(), CURTIME(), CURDATE()
select UPPER(name) from students
select lower(name) from students
select now()
select curtime()
select curdate()

10. LEFT, RIGHT, MID


select left(name, 4) from students, right(name, 4), mid(name, 3,6) from students

Group By Query
select sid, sum(amount) from fees group by sid //it will arrange data after grouping by sid

select dept, sum(salary) as total_salary from faculty group by dept

select city, count(city) from students group by city

Error will come in below command (we cannot join aggregate query with where clause)
Select dept, sum(salary) as "Total Salary" from faculty group by dept where
sum(salary)>150000

Having Clause

1. We can't use aggregate functions after where clause.


2. where works fast than having.
3. where loads only those records which match the criteria while having loads
all the records in memory then display those records which match the criteria.

Select dept, sum(salary) as total_salary from faculty group by dept having sum(salary) >
60000

Select dept, sum(salary) as total_salary from faculty group by dept having dept =
"Accounts" or dept = "Marketing"

select dept, min(salary), max( salary ) , sum( salary ) FROM faculty group by dept

Page 68 / 86
selectdept, sum(salary) as total_salary from faculty group by dept order by
total_salarydesc

selectdept, sum(salary) as total_salary from faculty group by dept order by


total_salarydesc limit 2

select students.id, students.fname, students.lname,sum(fees.amount) from students, fees


where students.id=fees.sid group by students.id order by sum(fees.amount) desc limit 1

Nested Query
select * from faculty where salary = (select max(salary) from faculty)
select * from fees where amount = (select max(amount) from fees)
select id, name, salary from faculty where salary =(select max(salary) from faculty)

Join Tables

Display All Records

select table1.fieldname, table2.fieldname,... from table1, table2 where table1.commonfield


= table2.commonfield

SELECT * from students, fees where students.id=fees.sid

select students.id, students.fname, students.lname, students.city, fees.id as ReceiptNo,


fees.amount, fees.dod from students, fees where students.id=fees.sid

select s.id, s.fname, s.lname, s.city, f.fid as ReceiptNo, f.amount, f.dod from student as s,
fees as f where s.id=f.sid

select students.id, students.fname, students.lname, students.city, sum(fees.amount) as


TotalFees, fees.dod from students, fees where students.id=fees.sid group by students.id

OR

select table1.fieldname, table2.fieldname from table1 INNER JOIN table2 ON


table1.commonfield = table2.commonfield

select students.id, students.fname, students.lname, students.city, sum(fees.amount) as


TotalFees from students inner join fees on students.id=fees.sid group by students.id

Page 69 / 86
select course.name as "Course Name", registration.dor as "Date of Registration",
course.fees as "Course Fees" from course, registration where course.id=registration.cid
and registration.sid=301

select students.id, students.fname, students.lname, students.city, fees.amount, fees.dod


from students, fees where students.id=fees.sid and (students.id=1000)

select students.id, students.fname, students.lname,students.city, fees.amount, fees.dod


from students, fees where students.id=fees.sid and (students.id=1000 or students.id=1001)

select students.id, students.fname, students.lname,sum(fees.amount) from students, fees


where students.id=fees.sid group by students.id

select students.id, students.fname, students.lname,sum(fees.amount) from students, fees


where students.id=fees.sid and(students.id=1000) group by students.id
select students.id, students.fname, students.lname,fees.amount, fees.dod from students,
fees where students.id = fees.sid and fees.amount>= 500
select students.id, students.fname, students.lname,fees.amount, fees.dod from students,
fees where students.id = fees.sid and students.name like 'm%'
select students.id, students.fname, students.lname,fees.amount, fees.dod from students
INNER JOIN fees ON students.id = fees.sid where students.name like 'm%'

Joining 3 tables
SELECT students.fname, students.lname,students.city, fees.amount, fees.dod,
course.name, course.duration FROM students INNER JOIN fees on students.id = fees.sid
INNER JOIN course on course.id = fees.cid

select fees.id as "Fees Id", students.id as "Student Id", students.fname,


students.lname,course.id as "Course Id", course.name as "Course Name", fees.amount,
fees.dod as "Date of Deposit" from students inner join fees on students.id=fees.sid inner
join course on course.id=fees.cid

Page 70 / 86
LEFT OUTER JOIN

course students

select course.cid, course.cname, course.fees, students.sid, students.sname, students.gender


from course left outer join students on course.cid=students.cid

Page 71 / 86
select students.sid, students.sname, students.gender, course.cid, course.cname, course.fees
from students left outer join course on students.cid=course.cid

RIGHT OUTER JOIN


select students.sid, students.sname, students.gender, course.cid, course.cname, course.fees
from students right outer join course on students.cid=course.cid

select course.cid, course.cname, course.fees, students.sid, students.sname, students.gender from course


right outer join students on course.cid=students.cid

SELECT fees.fid AS "Fees Id", students.sid AS "Student Id", students.sname, fees.amount, fees.dod AS
"Date of Deposit" FROM fees RIGHT OUTER JOIN students ON fees.sid = students.sid

Page 72 / 86
The SQL DISTINCT keyword is used in conjunction with SELECT statement to eliminate all the
duplicate records and fetching only unique records.

There may be a situation when you have multiple duplicate records in a table. While fetching such
records, it makes more sense to fetch only unique records instead of fetching duplicate records.

Syntax:
The basic syntax of DISTINCT keyword to eliminate duplicate records is as follows:

SELECT DISTINCT column1, column2,.....columnN


FROM table_name
WHERE [condition]

SELECT DISTINCT City FROM students

Assignments
1) Display all students where Date of Birth year is 1990.
2) Display name, coursenameand fee where course status is Active.
3) Display all the information where student has selected course PHP
4) Update city to Ajmer where city equals to Jaipur.
5) Insert two records in student table.
6) Delete record where city equals to blank.
Assignments
01) Add gender field in student default value should be male.

Page 73 / 86
02) Drop the primary key from student.
03) Make id field of student table again primary.
04) Display all the students who are registered for courses java and php. 10003
10015
05) Display all the students who are registered for more than two courses.
Database connectivity with form

mysql_connect(host, user, password)


It accepts hostname, username, password and returns true if connection successfully
otherwise returns empty string.

mysql_select_db("databasename")
It opens database. If opens successfully returns true otherwise empty string.

mysql_query("query")
it executes Query. It returns true if executes DML query It returns result set in case of
Select Query. It returns false if find any error in query.

mysql_affected_rows()
It returns how many rows are inserted or updated or deleted.

mysql_insert_id()
It returns newly generated id

After firing selected query, we can fetch records by following ways:

mysql_num_rows($recordSet)
It returns total records fetched by Query.

mysql_fetch_row($recordSet)
It returns one row from record set and move cursor to next row.
Here we can access each field by index number (<?= $row[0] ?>) and index starts with 0.
If don't find any records or reached at EOF (End of File) returns null or false.

mysql_fetch_assoc($recordSet)
It returns a record and move cursor to next record.
Here we can access each field by fieldname (<?= $row["id"] ?>). If don't find any records
or reached at EOR (End of Record) returns null or false.

mysql_fetch_array($recordSet)
Page 74 / 86
It returns a record and move the cursor to the next record.
Here we can access each field by fieldname (<?= $row["id"] ?>) or index number (<?
= $row[0] ?>). If don't find any records or reached at EOR (End of Record) returns null or
false.

mysql_fetch_object($recordSet)
It returns a record and move the cursor to the next record.
Here we can access each field by fieldname. If don't find any records or reached at EOR
(End of Record) returns null or false. We have to use pointer sign (->) for displaying
records from array like <?= $row->id ?>

mysql_error()
This function returns error message if mysql has an error otherwise false. blank or 0
means false.

die("String")
It prints the message and stops the program execution.

<?php
error_reporting(0);
$connection=mysql_connect("localhost","root","");
if(empty($connection)){
//echo "Could not connect with server";
die("Could not connect with server");
}else{
echo "Connect with server"."<br/>";
}

$db=mysql_select_db("ibirds");
if(empty($db)){
echo "Database not found";
}else{
echo "Open Database"."<br/>";
}

//Insert Records Example


/*
$query = "insert into students(fname, lname, city, dob, gender) values('Asif',
'Khan', 'Kota', '1997-01-16', 'Male')";

echo $query . "<hr/>";


Page 75 / 86
$result=mysql_query($query);
/*
if($result){
//echo "Id is => " . mysql_insert_id() . " <hr/>"; //in case of primary key and
auto increment
echo "Record Inserted Successfully.";
}else{
echo "Failed to Insert Record!<br/>";
//echo "Error: " . mysql_error() . " <hr/>"; //it displays mysql errors
(display in sql window)
}
//blank means false
if(mysql_error() == false){
echo "<hr/>Record Inserted Successfully.";
}else{
echo "Failed to Insert Record!<hr/>";
echo "Error: " . mysql_error() . " <hr/>";
}

//mysql_affected_rows()-->It returns how many rows are inserted or updated or


deleted.
$rows = mysql_affected_rows();
echo "<br/>Total Records Inserted: " . $rows;

//Update Records Example

$query = "update students set fname = 'Shekhar where id = 1";

echo $query . "<hr/>";


$result = mysql_query($query);

$rows = mysql_affected_rows();

echo "Total Records Updated = $rows <br/>";

if(mysql_error() == false){
echo "Record Updated Successfully.";
}else{
echo "Failed to Updated Record!<hr/>";
echo mysql_error();

Page 76 / 86
}*/
?>
<h3>Fatch Row</h3>
<?php
//Fetching Records
//fetch row
$query="select * from course";
$data=mysql_query($query);
echo "Total Number of records fatched ==>> ".mysql_num_rows($data);
?>
<table border="1px" align="center">
<tr>
<th>Course Id</th>
<th>Course Name</th>
<th>Fees</th>
<th>Duration</th>
<th>Status</th>
</tr>
<?php
//$row=mysql_fetch_row($data); //first of all we have to fetch only one record
and display it.
while($row = mysql_fetch_object($data)){
?>
<tr>
<td><?= $row->id ?</td>
<td><?= $row->name ?></td>
<td><?= $row->fees ?></td>
<td><?= $row->duration ?></td>
<td><?= $row->status ?></td>
</tr>
<?php
}
?>
</table>

Page 77 / 86
students.php

<?php
error_reporting(0);
mysql_connect("localhost", "root", "") or die("Could not connect with server!!!
<br/>");
mysql_select_db("college") or die("Could not open database!!!<br/>");
$query="select * from students";
if(!empty($_REQUEST['search'])){
$search = $_REQUEST['search'];
$query.=" where fname like '%$search%' || lname like '%$search%' || city like '%
$search%'";
}
$data=mysql_query($query);
?>
<form action="insert.php">
<table border="1px" align="center">
<tr>
<th>First Name</th>
<td><input type="text" name="fname"/></td>
</tr>
<tr>
<th>Last Name</th>
<td><input type="text" name="lname"/></td>
</tr>
<tr>
<th>City</th>
<td><input type="text" name="city"/></td>
</tr>
<tr>
<th>Date of Birth</th>
<td><input type="text" name="dob"/></td>
</tr>
<tr>
<th>Gender</th>
<td>
<input type="radio" name="gender" value="Male"/>Male
<input type="radio" name="gender" value="Female"/>Female
Page 78 / 86
</td>
</tr>
<tr>
<th colspan="2"><input type="submit" value="Insert Record"/></th>
</tr>
</table>
</form>
<form>
<table align="center">
<tr>
<td>
Search Record : <input type="text" name="search"/><input
type="submit" value="Submit Form"/>
</td>
</tr>
</table>
</form>
<table border="1px" align="center">
<tr>
<th>Student's Id</th>
<th>Name</th>
<th>City</th>
<th>Date of Birth</th>
<th>Gender</th>
<th>Action</th>
</tr>
<? while($row=mysql_fetch_object($data)){ ?>
<tr>
<td><?= $row->id ?></td>
<td><?= $row->fname." ".$row->lname ?></td>
<td><?= $row->city ?></td>
<td><?= $row->dob ?></td>
<td><?= $row->gender ?></td>
<td>
<a href="edit.php?id=<?= $row->id ?>">Edit/</a>
<a href="delete.php?id=<?= $row->id ?>" onClick="return confirm('Are you sure
to delete record??')">Delete</a>
</td>
</tr>
<? } ?>
Page 79 / 86
</table>

insert.php
<?php
error_reporting(0);
mysql_connect("localhost", "root", "") or die("Could not connect with server!!!
<br/>");
mysql_select_db("college") or die("Could not open database!!!<br/>");
$fname=$_REQUEST['fname'];
$lname=$_REQUEST['lname'];
$city=$_REQUEST['city'];
$dob=$_REQUEST['dob'];
$gender=$_REQUEST['gender'];
$query="insert into students(fname, lname, city, dob, gender) values('$fname',
'$lname', '$city', '$dob', '$gender')";
mysql_query($query);
header("location:students.php");
?>

delete.php

<?php
error_reporting(0);
mysql_connect("localhost", "root", "") or die("Could not connect with server!!!
<br/>");
mysql_select_db("college") or die("Could not open database!!!<br/>");
$id=$_REQUEST['id'];
$query="delete from students where id=$id";
mysql_query($query);
header("location:students.php");
?>

Page 80 / 86
edit.php
<?php
error_reporting(0);
mysql_connect("localhost", "root", "") or die("Could not connect with server!!!
<br/>");
mysql_select_db("college") or die("Could not open database!!!<br/>");
$id=$_REQUEST['id'];
if(!empty($id)){
$dt=mysql_query("select * from students where id=$id");
$rw=mysql_fetch_object($dt);
}
?>
<form action="update.php">
<input type="hidden" name="id" value="<?= $id?>"/>
<table border="1px" align="center">
<tr>
<th>First Name</th>
<td><input type="text" name="fname" value="<?= $rw->fname?>"/></td>
</tr>
<tr>
<th>Last Name</th>
<td><input type="text" name="lname" value="<?= $rw->lname?>"/></td>
</tr>
<tr>
<th>City</th>
<td><input type="text" name="city" value="<?= $rw->city?>"/></td>
</tr>
<tr>
<th>Date of Birth</th>
<td><input type="text" name="dob" value="<?= $rw->dob?>"/></td>
</tr>
<tr>
<th>Gender</th>
<td>
<input type="radio" name="gender" value="Male" <?= $rw-
>gender=='Male'?'checked':'' ?>/>Male
<input type="radio" name="gender" value="Female" <?= $rw-
>gender=='Female'?'checked':'' ?>/>Female
Page 81 / 86
</td>
</tr>
<tr>
<th colspan="2"><input type="submit" value="Update Record"/></th>
</tr>
</table>
</form>

update.php
<?php
error_reporting(0);
mysql_connect("localhost", "root", "") or die("Could not connect with server!!!
<br/>");
mysql_select_db("zakir") or die("Could not open database!!!<br/>");
$id=$_REQUEST['id'];
$fname=$_REQUEST['fname'];
$lname=$_REQUEST['lname'];
$city=$_REQUEST['city'];
$dob=$_REQUEST['dob'];
$gender=$_REQUEST['gender'];
$query="update students set fname='$fname', lname='$lname', city='$city',
dob='$dob',gender= '$gender' where id=$id";
mysql_query($query);
header("location:students.php");
?>

Page 82 / 86
onepage.php
<?php
error_reporting(0);
mysql_connect("localhost", "root", "") or die("Could not connect with server!!!
<br/>");
mysql_select_db("zakir") or die("Could not open database!!!<br/>");
$query="select * from students";
$button="Insert";

//Insert Record
if((!empty($_REQUEST['fname'])) && empty($_REQUEST['id'])) {
$fname=$_REQUEST['fname'];
$lname=$_REQUEST['lname'];
$city=$_REQUEST['city'];
$dob=$_REQUEST['dob'];
$gender=$_REQUEST['gender'];
mysql_query("insert into students(fname, lname, city, dob, gender) values('$fname',
'$lname', '$city', '$dob', '$gender')");
$fileName=mysql_insert_id();
$fileLoc=$_FILES['img']['tmp_name'];
move_uploaded_file($fileLoc, "images/$fileName.jpg");
header("location:onepage.php");
}

//Edit Record
if(!empty($_REQUEST['id'])){
$button="Update";
$id=$_REQUEST['id'];
$edata=mysql_query("select * from students where id=$id");
$rdata=mysql_fetch_object($edata);
}

//Update Record
if((!empty($_REQUEST['fname'])) && !empty($_REQUEST['id'])) {
$id=$_REQUEST['id'];
$fname=$_REQUEST['fname'];
$lname=$_REQUEST['lname'];
$city=$_REQUEST['city'];
Page 83 / 86
$dob=$_REQUEST['dob'];
$gender=$_REQUEST['gender'];
mysql_query("Update students set fname='$fname', lname='$lname', city='$city',
dob='$dob', gender='$gender' where id='$id'");
$fileLoc=$_FILES['img']['tmp_name'];
move_uploaded_file($fileLoc, "images/$id.jpg");
header("location:onepage.php");
}

//Delete Record
if(!empty($_REQUEST['del'])){
$del=$_REQUEST['del'];
mysql_query("delete from students where id=$del");
unlink("images/$del.jpg");
header("location:onepage.php");
}

//Search Record
if(!empty($_REQUEST['search'])){
$search = $_REQUEST['search'];
$query.=" where fname like '%$search%' || lname like '%$search%' || city like '%
$search%'";
}
$data=mysql_query($query);
?>

<form enctype="multipart/form-data" method="post">


<input type="hidden" name="id" value="<?= $id ?>"/>
<table border="1px" align="center">
<tr>
<th>First Name</th>
<td><input type="text" name="fname" value="<?= $rdata->fname ?>" /></td>
</tr>
<tr>
<th>Last Name</th>
<td><input type="text" name="lname" value="<?= $rdata->lname ?>"/></td>
</tr>
<tr>
<th>City</th>
<td><input type="text" name="city" value="<?= $rdata->city ?>"/></td>
Page 84 / 86
</tr>
<tr>
<th>Date of Birth</th>
<td><input type="text" name="dob" value="<?= $rdata->dob ?>"/></td>
</tr>
<tr>
<th>Gender</th>
<td>
<input type="radio" name="gender" value="Male" <?= $rdata-
>gender=='Male'?'checked':'' ?>/>Male
<input type="radio" name="gender" value="Female" <?= $rdata-
>gender=='Female'?'checked':'' ?>/>Female
</td>
</tr>
<tr>
<th>Upload Image</th>
<td><input type="file" name="img"/></td>
</tr>
<tr>
<th colspan="2"><input type="submit" value="<?= $button ?>"/></th>
</tr>
</table>
</form>

<form>
<table align="center">
<tr>
<td>
Search Record : <input type="text" name="search"/><input
type="submit" value="Submit Form"/>
</td>
</tr>
</table>
</form>
<table border="1px" align="center">
<tr>
<th>Student's Id</th>
<th>Name</th>
<th>City</th>
<th>Date of Birth</th>
Page 85 / 86
<th>Gender</th>
<th>Image</th>
<th>Action</th>
</tr>
<? while($row=mysql_fetch_object($data)){ ?>
<tr>
<td><?= $row->id ?></td>
<td><?= $row->fname." ".$row->lname ?></td>
<td><?= $row->city ?></td>
<td><?= $row->dob ?></td>
<td><?= $row->gender ?></td>
<td><img src="images/<?=$row->id?>.jpg" height="100px" width="100px"></td>
<td>
<a href="?id=<?= $row->id ?>">Edit/</a>
<a href="?del=<?= $row->id ?>" onClick="return confirm('Are you sure to delete
record??')">Delete</a>
</td>
</tr>
<? } ?>
</table>

Page 86 / 86
Image Upload (image.php)

<form action="process.php" method="post" enctype="multipart/form-data">


<table border="1px" align="center">
<tr>
<th>Upload Image</th>
<td><input type="file" name="img"/></td>
<td><input type="submit" value="Upload Image"/></td>
</tr>
</table>
</form>

Image Upload (imageProcess.php)

<?php
$fileName = $_FILES['img']['name'];
$fileSize = $_FILES['img']['size'];
$fileType = $_FILES['img']['type'];
$fileLoc = $_FILES["img"]["tmp_name"];
$fileError = $_FILES["img"]["error"];
echo $fileName."<br/>";
echo $fileSize." Bytes"."<br/>";
echo $fileType."<br/>";
echo $fileLoc."<br/>";
echo $fileError;

if(file_exists("image/".$fileName)){
echo "<br/>Failed to upload file.!<br/>";
//die("File Aready Exists!");
unlink("image/".$fileName);
}
else{
move_uploaded_file($fileLoc, "image/".$fileName);
echo "<br/>File uploaded successfully.!";
}

?>
<img src="image/<?= $fileName ?>" height="500px" width="500px"/>
Page 87 / 86
session (login.php)
<?php
error_reporting(0);
$msg = $_REQUEST['msg'];
?>
<html>
<head>
<meta charset="utf-8">
<title>Login Page</title>
</head>

<body>
<h1><?=$msg?></h1>
<form action="process.php" method="get">
<table>
<tr>
<th>Select User Type</th>
<td>
<select name="type">
<option value="admin">admin</option>
<option value="student">student</option>
</select>
</td>
</tr>
<tr>
<th>User Name</th>
<td><input type="text" name="uname"/></td>
</tr>
<tr>
<th>Password</th>
<td><input type="password" name="password"/></td>
</tr>
<tr>
<th>Submit Form</th>
<td><input type="submit" value="Submit"/></td>
</tr>
</table>
</form>
</body>
</html>
Page 88 / 86
process.php
<?php
session_start();
$uname = $_REQUEST['uname'];
$password = $_REQUEST['password'];
$type = $_REQUEST['type'];
if($uname=='admin' && $password=='root'){
$_SESSION['name']=$uname;
$_SESSION['pass']=$password;
$_SESSION['type']=$type;
if($type=='admin'){
header("location:home.php");
}
elseif($type=='student'){
header("location:about.php");
}
}
else
{
$error="User name or password incorrect";
header("location:login.php?msg=$error");
}
?>

home.php
<?php
session_start();
if(empty($_SESSION['name'])) header("location:login.php");
else
{
$type = $_SESSION['type'];
$user = $_SESSION['name'];
$password = $_SESSION['pass'];
}
?>
<h1>This is my home page</h1>
<h2>Login Type : <?= $type ?></h2>
<h2>Welcome : <?= $user ?></h2>
<h3>Password : <?= $password ?></h3>
<a href="logout.php">Logout</a>
Page 89 / 86
about.php
<?php
session_start();
if(empty($_SESSION['name'])) header("location:login.php");
else
{
$type = $_SESSION['type'];
$user = $_SESSION['name'];
$password = $_SESSION['pass'];
}
?>
<h1>This is my about us page</h1>
<h1>This is my home page</h1>
<h2>Login Type : <?= $type ?></h2>
<h2>Welcome : <?= $user ?></h2>
<h3>Password : <?= $password ?></h3>
<a href="logout.php">Logout</a>

logout.php
<?php
session_start();
session_destroy();
header("location:login.php");
?>

Page 90 / 86

S-ar putea să vă placă și