Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
26 views87 pages

PHP Conv

php mysql
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views87 pages

PHP Conv

php mysql
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 87

Unit I

Unit I : Building Blocks of PHP:-

Introduction to PHP:
Page | 1
PHP is a recursive acronym for "PHP: Hypertext Preprocessor". Rasmus Lerdorf
unleashed the first version of PHP way back in 1994. The PHP Hypertext
Preprocessor (PHP) is a programming language that allows web developers to create
dynamic content that interacts with databases. PHP is basically used for developing
web based software applications.

PHP is a server side scripting language that is embedded in HTML. It is integrated


with a number of popular databases, including MySQL, PostgreSQL, Oracle, Sybase,
Informix, and Microsoft SQL Server.

Example PHP program:

<html>
<body>
<?php
// Use echo to print on console
echo ―Hello World‖;
?>
</body>
</html>

Comments in PHP
// Single line comment (C++ and Java-style comment)
# Single line comment (Shell-style comments)
/* Multiple line comment (C-style comments) */

VARIABLES
The main way to store information in the middle of a PHP program is by using a
variable.

Here are the most important things to know about variables in PHP.

1. All variables in PHP are denoted with a leading dollar sign ($).
2. Variables are assigned with the = operator, with the variable on the left-hand
side and the expression to be evaluated on the right.

3. Variables can, but do not need, to be declared before assignment.


Unit I

4. Variables in PHP do not have intrinsic types - a variable does not know in
advance whether it will be used to store a number or a string of characters.

5. Variables used before they are assigned have default values. Page | 2

Syntax:
$var_name = value;
Ex :
<html>
<body>
<?php
$a = 25; // Numerical variable
$b = ―Hello‖; // String variable
$c = 5.7; // Float variable
echo ―Number is : ―.$a.
―<br/>‖; echo ―String is : ―.
$b. ―<br/>‖; echo ―Float value
:‖ .$c;
?>
</body>
<html>
ECHO and PRINT statements in PHP
- It can output one or more strings
– It can only output one string, and returns always 1

u need to output data through a function, you can use PRINT() instead:

DATA TYPES

PHP has a total of eight data types which we use to construct our variables –
Simple Types:
 Integers − are whole numbers, without a decimal point, like 4195.
 Float or Double − are floating-point numbers, like 3.14159 or 49.1.
 Booleans − have only two possible values either true or false.
 NULL − is a special type that only has one value: NULL.

 Strings − are sequences of characters.


Page | 3
Unit I

Compound Types:
 Arrays − are named and indexed collections of other values.
Page | 4
 Objects − are instances of programmer-defined classes, which can package up
both other kinds of values and functions that are specific to the class.
 Resources − are special variables that hold references to resources external to
PHP (such as database connections).
Integers:-

 An integer data type is a non-decimal number between -2,147,483,648 and


2,147,483,647. An integer must have at least one digit
 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)

Syntax: <variable_name> = value;

Ex: $int_var=12345;

Float or Double:

A float (floating point number) is a number with a decimal point or a number in


exponential form.

Ex:

$many=2.8855;

Boolean:

A Boolean represents two possible states: TRUE or FALSE.

$x = true;
$y = false;
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.
Example:

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

echo $x;
echo "<br>";
echo $y;
?> Page | 5

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.

Example:
<?php
$x = "Hello world!";
$x = null;
var_dump($x);
?>

OPERATORS IN PHP
Operators are symbols that tell the PHP processor to perform certain actions. For
example, the addition (+) symbol is an operator that tells PHP to add two variables or
values, while the greater-than (>) symbol is an operator that tells PHP to compare two
values.
The following lists describe the different operators used in PHP.

Arithmetic Operators
The arithmetic operators are used to perform common arithmetical operations, such as
addition, subtraction, multiplication etc. Here's a complete list of PHP's arithmetic
operators:
Operator Description Example Result

+ Addition $x + $y Sum of $x and $y


- Subtraction $x - $y Difference of $x and $y.
* Multiplication $x * $y Product of $x and $y.
/ Division $x / $y Quotient of $x and $y
% Modulus $x % $y Remainder of $x divided by $y

Example:
Unit I

<?php
$x = 10;
$y = 4;
Page | 6
echo($x + $y); // 0utputs: 14
echo($x - $y); // 0utputs: 6
echo($x * $y); // 0utputs: 40
echo($x / $y); // 0utputs: 2.5
echo($x % $y); // 0utputs: 2
?>

Assignment Operators

The assignment operators are used to assign values to variables.


Operator Description Example Is The Same As

= Assign $x = $y $x = $y
+= Add and assign $x += $y $x = $x + $y
-= Subtract and assign $x -= $y $x = $x - $y
*= Multiply and assign $x *= $y $x = $x * $y
/= Divide and assign quotient $x /= $y $x = $x / $y
%= Divide and assign modulus $x %= $y $x = $x % $y

Example:
<?php
$x = 10;
echo $x; // Outputs: 10
$x = 20;
$x += 30;
echo $x; // Outputs: 50
$x = 50;
$x -= 20;
echo $ ; // Outputs: 30
$x = 5;
$x *= 25;
echo $x; // Outputs: 125
$x = 50;
$x /= 10;
echo $x; // Outputs: 5
Unit I

$x = 100;
$x %= 15;
echo $x; // Outputs: 10
Page | 7
?>

Comparison Operators:

The comparison operators are used to compare two values in a Boolean fashion.
Operator Name Example Result

== Equal $x == $y True if $x is equal to $y


=== Identical $x === $y True if $x is equal to $y, and they are of
the same type
!= Not equal $x != $y True if $x is not equal to $y
<> Not equal $x <> $y True if $x is not equal to $y
!== Not identical $x !== $y True if $x is not equal to $y, or they are
not of the same type
< Less than $x < $y True if $x is less than $y

> Greater than $x > $y True if $x is greater than $y

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

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

Example:
<?php
$x = 25;
$y = 35;
$z = "25";
var_dump($x == $z); // Outputs: boolean true
var_dump($x === $z); // Outputs: boolean false
var_dump($x != $y); // Outputs: boolean true
var_dump($x !== $z); // Outputs: boolean true
var_dump($x < $y); // Outputs: boolean true
var_dump($x > $y); // Outputs: boolean false
var_dump($x <= $y); // Outputs: boolean true
var_dump($x >= $y); // Outputs: boolean false
?>
Unit I

Incrementing and Decrementing Operators:


Page | 8
The increment/decrement operators are used to increment/decrement a variable's
value.
Operator Name Effect

++$x Pre-increment Increments $x by one, then returns $x


$x++ Post-increment Returns $x, then increments $x by one
--$x Pre-decrement Decrements $x by one, then returns $x
$x-- Post-decrement Returns $x, then decrements $x by one

Example
<?php
$x = 10;
echo ++$x; // Outputs: 11
echo $x; // Outputs: 11
$x = 10;
echo $x++; // Outputs: 10
echo $x; // Outputs: 11
$x = 10;
echo --$x; // Outputs: 9
echo $x; // Outputs: 9
$x = 10;
echo $x--; // Outputs: 10
echo $x; // Outputs: 9
?>

Logical Operators:

The logical operators are typically used to combine conditional statements.


Operator Name Example Result

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


or Or $x or $y True if either $x or $y is true
xor Xor $x xor $y True if either $x or $y is true, but not both
&& And $x && $y True if both $x and $y are true
Unit I

|| Or $x || $y True if either $$x or $y is true


! Not !$x True if $x is not true
Page | 9
Example:
<?php
$year = 2014;
// Leap years are divisible by 400 or by 4 but not 100
if(($year % 400 == 0) || (($year % 100 != 0) && ($year % 4 == 0)))
{
echo "$year is a leap year.";
}
else
{
echo "$year is not a leap year.";
}
?>

String Operators:

There are two operators which are specifically designed for strings.
Operator Description Example Result

. Concatenation $str1 . $str2 Concatenation of $str1 and $str2


.= Concatenation assignment $str1 .= $str2 Appends the $str2 to the $str1

Example:
<?php
$x = "Hello";
$y = " World!";
echo $x . $y; // Outputs: Hello World!
$x .= $y;
echo $x; // Outputs: Hello World!
?>

Array Operators:

The array operators are used to compare arrays:


Operator Name Example Result
Unit I

+ Union $x + $y Union of $x and $y


== Equality $x == $y True if $x and $y have the same key/value pairs
Page | 10
=== Identity $x === $y True if $x and $y have the same key/value pairs in the
same order and of the same types
!= Inequality $x != $y True if $x is not equal to $y
<> Inequality $x <> $y True if $x is not equal to $y
!== Non- $x !== $y True if $x is not identical to $y
identity

Example:
<?php
$x = array("a" => "Red", "b" => "Green", "c" => "Blue");
$y = array("u" => "Yellow", "v" => "Orange", "w" => "Pink");
$z = $x + $y; // Union of $x and $y
var_dump($z);
var_dump($x == $y); // Outputs: boolean false
var_dump($x === $y); // Outputs: boolean false
var_dump($x != $y); // Outputs: boolean true
var_dump($x <> $y); // Outputs: boolean true
var_dump($x !== $y); // Outputs: boolean true
?>

Concatenation Operator:
The concatenation operator is represented by a single period (.). Treating both
operands as strings, this operator appends the right-side operand to the left-side
operand. So
―hello‖.‖ world‖

Returns

“hello world”

CONSTANT IN PHP
 A constant is a name or an identifier for a fixed value. Constant are like
variables except that once they are defined, they cannot be undefined or
changed.
Unit I

 Constants are very useful for storing data that doesn't change while the script is
running.
 Common examples of such data include configuration settings such as database
Page | 11
username and password, website's base URL, company name, etc.
 Constants are defined using PHP's define() function, which accepts two
arguments: the name of the constant, and its value.
 define(name, value, case-insensitive)
o name: Specifies the name of the constant
o value: Specifies the value of the constant
o case-insensitive: Specifies whether the constant name should be case-
insensitive. Default is false
 Once defined the constant value can be accessed at any time just by referring to
its name.

Example:
<?php
// Defining constant
define("SITE_URL",
"https://www.tutorialrepublic.com/"); // Using constant
echo 'Thank you for visiting - ' . SITE_URL;
?>

PHP CONDITIONAL STATEMENTS


Like most programming languages, PHP also allows you to write code that perform
different actions based on the results of a logical or comparative test conditions at run
time.
There are several statements in PHP that you can use to make decisions:
 The if statement
 The if...else statement
 The if...elseif....else statement
 The switch...case statement

The if Statement:
The if statement is used to execute a block of code only if the specified condition
evaluates to true. This is the simplest PHP's conditional statements and can be written
like:

if(condition){
// Code to be executed
}
Example:
Unit I

<?php
$d = date("D");
if($d == "Fri"){
echo "Have a nice weekend!"; Page | 12
}
?>
The if...else Statement:
You can enhance the decision making process by providing an alternative choice
through adding an else statement to the if statement. The if...else statement allows you
to execute one block of code if the specified condition is evaluates to true and another
block of code if it is evaluates to false.

if(condition)
{
// Code to be executed if condition is true
} else
{
// Code to be executed if condition is false
}
Example:
<?php
$d = date("D");
if($d == "Fri")
{
echo "Have a nice weekend!";
} else{
echo "Have a nice day!";
}
?>

The if...elseif...else Statement:


The if...elseif...else a special statement that is used to combine
multiple if...else statements.

if(condition)
{
// Code to be executed if condition is true
} else if(condition)
{
// Code to be executed if condition is true
} else
{
// Code to be executed if condition is false
}
Unit I

Example:
<?php
$d = date("D"); Page | 13
if($d == "Fri")
{
echo "Have a nice weekend!";
} elseif($d == "Sun")
{
echo "Have a nice Sunday!";
} else
{
echo "Have a nice day!";
}
?>

The Ternary Operator:


The ternary operator provides a shorthand way of writing the if...else statements. The
ternary operator is represented by the question mark (?) symbol and it takes three
operands: a condition to check, a result for ture, and a result for false.

Example:

<?php echo ($age < 18) ? 'Child' : 'Adult'; ?>

Switch…Case:
The switch-case statement is an alternative to the if-elseif-else statement, which does
almost the same thing. The switch-case statement tests a variable against a series of
values until it finds a match, and then executes the block of code corresponding to that
match.

switch(n)
{
case label 1:
// Code to be executed if n=label1
break;
case label 2:
// Code to be executed if n=label2
break;
...
default:
// Code to be executed if n is different from all labels
}

Example:
Unit I

<?php
$today = date("D");
switch($today)
Page | 14
{
case "Mon":
echo "Today is Monday. Clean your house.";
break;
case "Tue":
echo "Today is Tuesday. Buy some food.";
break;
case "Wed":
echo "Today is Wednesday. Visit a doctor.";
break;
case "Thu":
echo "Today is Thursday. Repair your car.";
break;
case "Fri":
echo "Today is Friday. Party tonight.";
break;
case "Sat":
echo "Today is Saturday. Its movie time.";
break;
case "Sun":
echo "Today is Sunday. Do some rest.";
break;
default:
echo "No information available for that day.";
break;
}?
>

PHP Loops
Different Types of Loops in PHP
Loops are used to execute the same block of code again and again, until a certain
condition is met. The basic idea behind a loop is to automate the repetitive tasks
within a program to save the time and effort. PHP supports four different types of
loops.
 while — loops through a block of code until the condition is evaluate to true.
Unit I

do…while — the block of code executed once and then condition is evaluated. If
the condition is true the statement is repeated as long as the specified condition is true.
 for — loops through a block of code until the counter reaches a specified number.
Page | 15
 foreach — loops through a block of code for each element in an array.
PHP while Loop:
The while statement will loops through a block of code until the condition in
the whilestatement evaluate to true.
while(condition)
{
// Code to be executed
}
Example:
<?php
$i = 1;
while($i <= 3)
{
$i++;
echo "The number is " . $i . "<br>";
}
?>
PHP do…while Loop:
The do-while loop is a variant of while loop, which evaluates the condition at the end
of each loop iteration. With a do-while loop the block of code executed once, and then
the condition is evaluated, if the condition is true, the statement is repeated as long as
the specified condition evaluated to is true.
do{
// Code to be executed
}
while(condition);
Example:
<?php
$i = 1;
Do
{
$i++;
echo "The number is " . $i . "<br>";
}
while($i <= 3);
?>
Unit I

Difference Between while and do…while Loop:


The while loop differs from the do-while loop in one important way — with
a while loop, the condition to be evaluated is tested at the beginning of each loop
Page | 16
iteration, so if the conditional expression evaluates to false, the loop will never be
executed.
With a do-while loop, on the other hand, the loop will always be executed once, even
if the conditional expression is false, because the condition is evaluated at the end of
the loop iteration rather than the beginning.

PHP for Loop:


The for loop repeats a block of code until a certain condition is met. It is typically
used to execute a block of code for certain number of times.
for(initialization; condition; increment)
{
// Code to be executed
}

The parameters of for loop have following meanings:


 initialization — it is used to initialize the counter variables, and evaluated once
unconditionally before the first execution of the body of the loop.
 condition — in the beginning of each iteration, condition is evaluated. If it evaluates
to true, the loop continues and the nested statements are executed. If it evaluates
to false, the execution of the loop ends.
 increment — it updates the loop counter with a new value. It is evaluate at the end of
each iteration.

Example:
<?php
for($i=1; $i<=3; $i++)
{
echo "The number is " . $i . "<br>";
}
?>
PHP foreach Loop:
The foreach loop is used to iterate over arrays.
foreach($array as $value){
// Code to be executed
}
Unit I

Example:
<?php
$colors = array("Red", "Green", "Blue");
Page | 17

// Loop through colors array


foreach($colors as $value){
echo $value . "<br>";
}
?>

There is one more syntax of foreach loop, which is extension of the first.
foreach($array as $key => $value){
// Code to be executed
}
Example:
<?php
$superhero = array(
"name" => "Peter Parker",
"email" => "[email protected]",
"age" => 18
);

// Loop through superhero array


foreach($superhero as $key => $value){
echo $key . " : " . $value . "<br>";
}
?>

PHP FUNCTIONS
A function is a self-contained block of code that can be called by your scripts. When
called, the function’s code is executed and performs a particular task. You can pass
values to a function, which then uses the values appropriately—storing them,
transforming
them, displaying them, whatever the function is told to do. When finished,
a function can also pass a value back to the original code that called it into action.
PHP Built-in Functions
PHP has a huge collection of internal or built-in functions that you can call directly
within your PHP scripts to perform a specific task, like gettype(), print_r(), var_dump,
etc.
PHP User-Defined Functions
Unit I

n addition to the built-in functions, PHP also allows you to define your own functions.
It is a way to create reusable code packages that perform specific tasks and can be
kept and maintained separately form main program. Here are some advantages of
Page | 18
using functions:
 Functions reduces the repetition of code within a program
 Functions makes the code much easier to maintain
 Functions makes it easier to eliminate the errors
 Functions can be reused in other application

Creating and Invoking Functions:


The basic syntax of creating a custom function can be give with:
function functionName()
{
// Code to be executed
}
The declaration of a user-defined function start with the word function, followed by
the name of the function you want to create followed by parentheses i.e. () and finally
place your function's code between curly brackets {}.

Example:
<?php
// Defining function
function saikiran()
{
echo "welome to my world‖;
}
// Calling function
saikiran();
?>

Note:A function name must start with a letter or underscore character not with a
number, optionally followed by the more letters, numbers, or underscore characters.
Function names are case-insensitive.

Functions with Parameters:


You can specify parameters when you define your function to accept input values at
run time. The parameters work like placeholder variables within a function; they're
replaced at run time by the values (known as argument) provided to the function at the
time of invocation.
Unit I

function myFunc($oneParameter, $anotherParameter)


{
// Code to be executed Page | 19
}
You can define as many parameters as you like. However for each parameter you
specify, a corresponding argument needs to be passed to the function when it is called.

Example:
<?php
// Defining function
function getSum($num1, $num2)
{
$sum = $num1 + $num2;
echo "Sum of the two numbers $num1 and $num2 is : $sum";
}

// Calling function
getSum(10, 20); ?
>

Returning Values from a Function:


A function can return a value back to the script that called the function using the
return statement. The value may be of any type, including arrays and objects.
Example:

<?php
// Defining function
function getSum($num1, $num2)
{
$total = $num1 + $num2;
return $total;
}
// Printing returned value
echo getSum(5, 10); // Outputs: 15
?>

UNDERSTANDING THE VARIABLE SCOPE


However, you can declare the variables anywhere in a PHP script. But, the location of
the declaration determines the extent of a variable's visibility within the PHP program
Unit I

i.e. where the variable can be used or accessed. This accessibility is known as variable
scope.
By default, variables declared within a function are local and they cannot be viewed or
Page | 20
manipulated from outside of that function, as demonstrated in the example below:

Example:
<?php
// Defining function
function test()
{
$greet = "Hello World!";
echo $greet;
}
test(); // Outputs: Hello World!
echo $greet; // Generate undefined variable error
?>
The global Keyword:
There may be a situation when you need to import a variable from the main program
into a function, or vice versa. In such cases, you can use the global keyword before the
variables inside a function. This keyword turns the variable into a global variable,
making it visible or accessible both inside and outside the function, as show in the
example below:
Example:
<?php
$greet = "Hello
World!"; // Defining
function
function test()
{
global $greet;
echo $greet;
}
test();
echo $greet;
$greet = "Goodbye";
test();
echo $greet;
?>
Page | 21
Unit I

Saving State Between Function Calls with the static Statement:


If you declare a variable within a function in conjunction with the static statement, the
variable remains local to the function, and the function ―remembers‖ the value of the
Page | 22
variable from execution to execution.
Example:
<?php
function keep_track()
{
STATIC $count = 0;
$count++;
print $count;
print "<br />";
}

keep_track();
keep_track();
keep_track();
?>

More About Arguments


Setting Default Values for Arguments
You can also create functions with optional parameters — just insert the parameter
name, followed by an equals (=) sign, followed by a default value, like this.

Example:
<?php
function customFont($font, $size=1.5)
{
echo "<p style=\"font-family: $font; font-size: {$size}em;\">Hello, world!</p>";
}
customFont("Arial", 2);
customFont("Times", 3);
customFont("Courier"); ?
>
Passing Variable References to Functions
In PHP there are two ways you can pass arguments to a function: by value and by
reference. By default, function arguments are passed by value so that if the value of
the argument within the function is changed, it does not get affected outside of the
function. However, to allow a function to modify its arguments, they must be passed
by reference.
Unit I

Passing an argument by reference is done by prepending an ampersand (&) to the


argument name in the function definition, as shown in the example below:

Page | 23
Example:
<?php
function selfMultiply(&$number)
{
$number = $number*$number;
return $number;
}
$mynum = 5;
echo $mynum; // Outputs: 5
selfMultiply($mynum);
echo $mynum; // Outputs: 25
?>
PHP Arrays:-
PHP array is an ordered map (contains value on the basis of key). It is used to hold multiple values of
similar type in a single variable. An array is a special variable that can hold many values under a single
name, and you can access the values by referring to an index number or name.
Page | 24
Advantage of PHP Array
Less Code: We don't need to define multiple variables.

Easy to traverse: By the help of single loop, we can traverse all the elements of an array.

Sorting: We can sort the elements of array.

PHP Array Types


There are 3 types of array in PHP.
 
Indexed Array

 
Associative Array 

 
Multidimensional Array

1. PHP Indexed Array


PHP index is represented by number which starts from 0. We can store number, string and object in the
PHP array. All PHP array elements are assigned to an index number by default.

There are two ways to define indexed array:

1st way:

Ex: $season=array("summer","winter","spring","autumn");

Program:

<?php

$season=array("summer","winter","spring","autumn");
echo "Season are: $season[0], $season[1], $season[2] and $season[3]";

?>

Output:

Season are: summer, winter, spring and autumn

2nd way:

Ex: $season[0]="summer";

$season[1]="winter";$season[2]="spring";
$season[3]="autumn";
Program:

<?php
$season[0]="summer";
$season[1]="winter";
$season[2]="spring"; Page | 25
$season[3]="autumn";

echo "Season are: $season[0], $season[1], $season[2] and $season[3]"; ?>

Output:

Season are: summer, winter, spring and autumn

2. PHP Associative Array


We can associate name with each array elements in PHP using => symbol.

There are two ways to define associative array:

1st way:

Ex: $salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"200000");

Program:

<?php

$salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"200000");
echo "Sonoo salary: ".$salary["Sonoo"]."<br/>"; echo "John salary: ".
$salary["John"]."<br/>";

echo "Kartik salary: ".$salary["Kartik"]."<br/>";


?>

Output:

Sonoo salary: 350000


John salary: 450000
Kartik salary: 200000

2nd way:

$salary["Sonoo"]="350000";
$salary["John"]="450000";

$salary["Kartik"]="200000";

Program:

<?php
$salary["Sonoo"]="350000";
$salary["John"]="450000";
$salary["Kartik"]="200000";
echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";
echo "John salary: ".$salary["John"]."<br/>";
echo "Kartik salary: ".$salary["Kartik"]."<br/>";
?>
Output:

Sonoo salary: 350000 Page | 26


John salary: 450000
Kartik salary: 200000

3. PHP Multidimensional Array


PHP multidimensional array is also known as array of arrays. It allows you to store tabular data in an
array.

PHP multidimensional array can be represented in the form of matrix which is represented by row *
column.

Definition

$emp = array
(

array(1,"sonoo",400000),
array(2,"john",500000),
array(3,"rahul",300000) )
;

Let's see a simple example of PHP multidimensional array to display following tabular data. In this
example, we are displaying 3 rows and 3 columns.

Id Name Salary

1 sonoo 400000

2 john 500000

3 rahul 300000

<?php
$emp = array
(
array(1,"sonoo",400000),
array(2,"john",500000),
array(3,"rahul",300000) )
;
for ($row = 0; $row < 3; $row++)

{
for ($col = 0; $col < 3; $col++)
{
echo $emp[$row][$col]." ";
}
echo "<br/>";
}

Page | 27
?>

Output:
1 sonoo 400000

2 john 500000
3 rahul 300000 Page | 28

PHP OBJECTS
Object-oriented programming (OOP) is a popular programming paradigm that allows developers to create
more organized, efficient, and modular code. PHP is a versatile language that supports OOP, Whether you
are a beginner or an experienced developer, understanding classes and objects in PHP is essential for
building scalable and maintainable web applications. If you're looking to hire PHP developers, make sure
they have a strong understanding of OOP principles.

PHP Classes and Objects?


In PHP, a class is a blueprint for creating objects. It defines a set of properties and methods to be used by the
objects created from the class. An object is an instance of a class, which means it has its own set of
properties and methods defined in the class.

Creating a PHP Class


To create a class in PHP, use the class keyword followed by the name of the class. The class name should be
in CamelCase (i.e., the first letter of each word is capitalized) and should be a noun that describes the
purpose of the class.

Syntax:

class MyClass

// Properties and methods go here

Defining Properties and Methods


Properties are variables that belong to a class, and methods are functions that belong to a class. To define
properties, use the public, private, or protected keyword followed by the property name. Similarly, to define
methods, use the public, private, or protected keyword followed by the method name and a pair of
parentheses.

class MyClass
{
public $property1;
private $property2;
protected $property3;
public function method1()
{
// Code goes here
}
private function method2()
{
// Code goes here
}
protected function method3()
{
// Code goes here Page | 29
}
}

Creating an Object

To create an object from a class, use the new keyword followed by the class name and a pair of parentheses.

Eg:

$object1 = new MyClass();

Accessing Properties and Methods

To access the properties and methods of an object, use the arrow operator (→) followed by the property or
method name. Keep in mind that you can only access public and protected properties and methods from
outside the class.

$object1→property1 = "Hello, world!";

echo $object1(→property1; // Output: Hello, world!

$object1(→method1();

Program:1

<?php
class SayHello
{
function hello()
{
echo "Hello World";
}
}
$obj=new SayHello;
$obj->hello();
?>
Output

Hello World

Program-2

<?php
$obj=new stdClass;
$obj→name="Deepak";
$obj→age=21;
$obj→marks=75;
echo $obj;
?>
Output

stdClass Object(

[name] => Deepak


Page | 30
[age] => 21

[marks] => 75

Program-3
<?php
$arr=array("name"=>"Deepak", "age"=>21, "marks"=>75);
$obj=(object)$arr;
echo $obj;
?>
Output
stdClass Object(
[name] => Deepak
[age] => 21
[marks] => 75
)
Program-4
<?php
$obj=new stdClass;
$obj->name="Deepak";
$obj->age=21;
$obj->marks=75;
$arr=(array)$obj;
echo $arr;
?>
Output

Array(
[name] => Deepak
[age] => 21
[marks] => 75
)
Program-5 <?
php
$name="Deepak";
$age=21;
$percent=75.50;
$obj1=(object)$name;
print_r($obj1);
$obj2=(object)$age;
print_r($obj2);
$obj3=(object)$percent;
print_r($obj3);
?>
Output
stdClass Object(
[scalar] => Deepak
)
stdClass Object(
[scalar] => 21 Page | 31
)
stdClass Object(
[scalar] => 75.5
)
Formatting strings with PHP
The sprintf() function is an inbuilt function in PHP that is used for formatting strings in a manner similar to
the C language’s printf() function. It allows you to create formatted strings by substituting placeholders with
corresponding values.
Syntax:
string sprintf(string $format, mixed ...$values)
Parameters: This function accepts two parameters that are described below:
$format: This is a string that specifies the format of the output. It contains placeholders that begin with a
percent sign (%) followed by a character representing the type of value that should be inserted at that
position.
$values: These are the values that will replace the placeholders in the format string. You can provide any
number of arguments, depending on the number of placeholders in the format string and their types.
Return Values: The sprintf() function returns the string which is produced by this function.

1. Concatenation
Use the dot (.) operator to concatenate strings.
$name = "sai";
$greeting = "Hello". $name;
echo $greeting;
// Outputs: Hello sai
2. String Interpolation
Use double quotes to embed variables within strings.
$name = "sai";
$greeting = "Hello, $name";
echo $greeting;
// Outputs: Hello, sai
3. sprintf()
Use sprintf() to format strings with placeholders.
$name = "saikiran";
$age = 30;
$greeting = sprintf("Hello, %s You are %d years old.", $name, $age);
echo $greeting;
// Outputs: "Hello, saikiran You are 30 years old."
4. printf()
Use printf() to format and print strings.
$name = "saikiran";
$age = 30;
printf("Hello, %s You are %d years old.", $name, $age);
// Outputs: "Hello, saikiran You are 30 years old."
5. String Formatting with Arrays
Use implode() to format strings with arrays.
$fruits = array("apple", "banana", "cherry");
$fruitList = implode(", ", $fruits);
echo $fruitList;
// Outputs: apple, banana, cherry

Program:
<?php
$name = "John";
$greeting = "Hello, " . $name; Page | 32
echo $greeting . "\n";
$greeting = "Hello, $name";
echo $greeting . "\n";
$age = 30;
$greeting = sprintf("Hello, %s! You are %d years old.", $name, $age);
echo $greeting . "\n";
printf("Hello, %s! You are %d years old.", $name, $age);
echo "\n";
$fruits = array("apple", "banana", "cherry");
$fruitList = implode(", ", $fruits);
echo "Fruit list: $fruitList\n";
echo "Uppercase: " . strtoupper($name) . "\n";
echo "Lowercase: " . strtolower($name) . "\n";
$text = " Hello World! ";
echo "Trimmed: '" . trim($text) . "'\n";
echo "Padded: '" . str_pad($text, 20, "*") . "'\n";
?>
This program demonstrates the following string formatting techniques:

 Concatenation
 String Interpolation
 sprintf()
 printf()
 String Formatting with Arrays
 Uppercase and Lowercase
 Trim and Pad
Investigating Strings with PHP& Manipulating Strings with PHP,
You do not always know everything about the data that you are working with. Strings can arrive from many
sources, including user input, databases, files, and Web pages. Before you begin to work with data from an
external source, you often will need to find out more about it. PHP provides many functions that enable you
to acquire information about strings.
<?php
$string = "Hello World!";
$length = strlen($string);
echo "Length: $length\n";
$position = strpos($string, "World");
echo "Position of 'World': $position\n";
$substring = substr($string, 6);
echo "Substring from position 6: $substring\n";
if (strpos($string, "World") !== false)
{
echo "String contains 'World'\n";
}
if (strpos($string, "Hello") === 0)
{
echo "String starts with 'Hello'\n";
}
if (substr($string, -5) === "World")
{
echo "String ends with 'World'\n";
}
$replaced = str_replace("World", "Universe", $string);
echo "String replaced with 'Universe': $replaced\n";
$uppercase = strtoupper($string);
$lowercase = strtolower($string); Page | 33
echo "Uppercase: $uppercase\n";
echo "Lowercase: $lowercase\n";
$trimmed = trim(" Hello World ");
echo "Trimmed string: $trimmed\n";
$fruits = explode(",", "apple,banana,cherry");
print_r($fruits);
?>
This program demonstrates the following string investigation techniques:
1. String Length
2. String Position
3. Substring
4. String Contains
5. String Starts With
6. String Ends With
7. String Replace
8. String Uppercase/Lowercase
9. String Trim
10. String Split
PHP Date and Time Functions:
the date/time functions allow you to get the date and time from the server where your PHP script runs. You
can then use the date/time functions to format the date and time in several ways.

Note: These functions depend on the locale settings of your server. Remember to take daylight saving time
and leap years into consideration when working with these functions.
Program:
<?php
echo "Current Date and Time: " . date("Y-m-d H:i:s") . "\n";
echo "Formatted Date: " . date("l, F j, Y") . "\n";
$timestamp = time();
echo "Timestamp: $timestamp\n";
echo "Converted Timestamp: " . date("Y-m-d H:i:s", $timestamp) . "\n";
echo "Date + 1 Week: " . date("Y-m-d", strtotime("+1 week")) . "\n";
date_default_timezone_set("America/New_York");
echo "Current Date and Time (New York): " . date("Y-m-d H:i:s") . "\n";
$date1 = new DateTime("2024-08-08");
$date2 = new DateTime("2024-08-15");
$interval = $date1->diff($date2);
echo "Date Interval: " . $interval->days . " days\n";
$start = new DateTime("2024-08-08");
$end = new DateTime("2024-08-15");
$interval = new DateInterval("P1D");
$period = new DatePeriod($start, $interval, $end);
echo "Date Period:\n";
foreach ($period as $date) {
echo $date->format("Y-m-d") . "\n";
}
?>
This program demonstrates the following date and time functions:
 Current Date and Time
 Formatting Dates
 Date Arithmetic
 Time Zones
 Date Interval
 Date Period Page | 34
Unit-III
PHP
PHP is an acronym for "Hypertext Preprocessor". It is a widely-used, open source scripting
language. This code can be executed on the server and the result is returned to the browser as plain
HTML. PHP files can contain text, HTML, CSS, JavaScript, and PHP code. PHP files have extension Page | 35
".php". You do not need to compile anything or install any extra tools php.
By using PHP we can generate dynamic page content which can collect form data and add, delete,
modify data in your database. PHP is not limited to output HTML. You can output images, PDF files,
and even flash movies. It can send and receive cookies and also control user-access.
PHP runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.) and compatible with
almost all servers used today (Apache, IIS, etc.) so it supports a wide range of databases. It is easy to
learn and runs efficiently on the server side.
Executing PHP Programs:
1. Install PHP and MySQL in your Computer.
2. First create your own directory inside WWW directory which is located
at Local Disc C Wamp server directory.
Like C:\wamp\www
3. Then just create some .php files, that should to be placed in that
directory.
4. Start WAMP server located at start menu and put it online:
5. Open Web browser and go for http://localhost/. It will show PHP
option Under Your Projects open PHP-it contains all the phpfiles.
Click on your required file. You do not need to compile by using any
tools. It will be automatically execute your PHP file.

PHP and MySQL 1 Prepared By: GiriBabu


Comments in PHP:
A comment in PHP code is a line that is not read/executed as part of the program. Its only purpose
is to be read by someone who is looking at the code.
PHP supports several ways of commenting:
<?php Page | 36
// This is a single-line comment
# This is also a single-line comment
/* This is a multiple-lines comment block
that spans over multiple lines
*/ ?>

PHP 5 Syntax:
 A PHP script is executed on the server, and the plain HTML result is sent back to the browser.
 A PHP file normally contains HTML tags, and some PHP scripting code.
 A PHP script can be placed anywhere in the document.
 A PHP script starts with <?php and ends with ?>
<?php
// PHP code goes here
?>
 The default file extension for PHP files is ".php".
 PHP statements end with a semicolon (;)
 PHP script that uses a built-in PHP function "echo" to output on a web page.
 In PHP, all keywords (e.g. if, else, while, echo, etc.), classes, functions, and user-defined
functions are NOT case-sensitive.
Ex: ECHO,echo are the same,
 However; all variable names are case-sensitive.
Ex: $color, $COLOR, and $coLOR are treated as three different variables.
 PHP is a Loosely Typed Language- we did not have to tell PHP which data type the variable is.
PHP automatically converts the variable to the correct data type, depending on its value.

Example:
<!DOCTYPE html>
<html>
<body>
<h1>My first PHP page</h1>
<?php
echo "welcome to PHP programming";
?>
</body>
</html>
PHP Variables:
Variables are "containers or entities" for storing some information. In PHP, a variable starts with
the $ sign, followed by the name of the variable.

PHP and MySQL 2 Prepared By: GiriBabu


Ex: $name= "GiriBabu";
$x = 5;
$y = 10.5;
When you assign a string values to a variable, put quotes around the value.
Note: Unlike other programming languages, PHP has no command for declaring a variable. It is
Page | 37
created the moment you first assign a value to it.
Rules for PHP variables:
 A variable starts with the $ sign, followed by the name of the variable
 A variable name must start with a letter or the underscore character
 A variable name cannot start with a number
 A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
 Variable names are case-sensitive ($name and $NAME are two different variables).
Output Variables:
In PHP echo statement is often used to output data to the screen.
Echo “$name";
echo “$x + $y”;

Ex: Program for sum of two numbers.


<!DOCTYPE html>
<html>
<body>
<?php
$x=25;
$y=35;
$sum=$x+$y;
echo "the sum is: $sum";
?>
</body>
</html>

PHP Variables Scope:


In PHP, variables can be declared anywhere in the script. The scope of a variable is the part of the
script where the variable can be referenced/used.
PHP has three different variable scopes:
1. Local scope
2. Global scope
3. Static scope
Global Scope:
A variable declared outside a function has a GLOBAL SCOPE and can only be accessed outside
a function: <?
php $x
= 5; // global scope
function myTest()

PHP and MySQL 3


{
echo “Value x inside fuction is: $x"; // global x used inside function generate an error
}
myTest();
echo " Value x outside fuction is: $x</p>"; //No error;
?> Page | 38
Local scope: A variable declared within a function has a LOCAL SCOPE and can only be accessed
within that function:
<?php
function myTest()
{
$x = 5; // local scope
echo "Value x inside function is: $x";
}
myTest();
echo "Value x outside function is: $x"; // local x used outside function generate an error
?>
Note:
1. You can have local variables with the same name in different functions or Same name as Global
variables because local variables are only recognized by the function in which they are declared.

2. The global keyword is used to access a global variable from within a function. To do this, use
the global keyword before the variables (inside the function):
<?php
$x = 5;
$y = 10;
function calculate()
{
global $x, $y;
$y = $x + $y;
}
calculate ();
echo $y;
?>
PHP also stores all global variables in an array called $GLOBALS[index].The indexholds the
name of the variable. This array is also accessible from within functions directly.
function caliculate()
{
$GLOBALS['y'] = $GLOBALS['x'] + $GLOBALS['y'];
}
Static scope:
Normally, when a function is completed / executed, all of its variable values are deleted.
However, sometimes we want a local variable value NOT to be deleted. We need it for a further job. To
do this, use the static keyword when you first declare the variable:
<?php
function calculate()
{
static $x = 123;
echo $x;
Page | 39
$x+
+; }
calculate ();
calculate ();
?>
PHP Data Types:
Variables are containers which can store data of different types. PHP supports the following data
types:
1. Integer
2. Float (floating point numbers - also called double)
3. Boolean
4. Array
5. String
6. Object
7. NULL
8. Resource
PHP Integer: An integer data type is a non-decimal number. An integer must have at least one
digit, must not have a decimal point. It can be either positive or negative. Range of integer between -
2,147,483,648 and 2,147,483,647
Ex: $x = 5985;
PHP Float: A float is a number with a decimal point or a number in exponential form.
Ex: $x = 59.85;
PHP Boolean: A Boolean represents two possible states: TRUE or FALSE. Booleans are often
used in conditional testing.
Ex: $x = true;
$y = false;
PHP Array: An array stores multiple values in one single variable in continuous memory locations.
Ex: $cars = array("Volvo","BMW","Toyota");
$x=array(12,34,56,67);
echo $x[2]
PHP String: A string is a sequence of characters inside quotes. You can use single or double quotes:
Ex: $x = "Giribabu";
$y = 'Giribabu';
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 = "VOLVO";
}
Page | 40
}
$vehicle = new Car(); // create an object
echo $vehicle->model; // show object properties
?>
PHP NULL Value: Null is a special data type value. That has no value assigned to it.
Ex: $x = null;
Note: If a variable is created without a value, it is automatically assigned a value of NULL.

PHP Constants: Constants are like variables except that once they are defined its values cannot be
changed or undefined during the script. A valid constant name starts with a letter or underscore , no $
sign before the constant name.
Note: Unlike variables, constants are automatically global across the entire script.
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("car", "VOLVO");
echo car;
?>
The example below creates a constant with a case-insensitive name:
<?php
define("car", "VOLVO", true);
echo car;
?>

PHP Operators: Operators are used to perform operations on operands (variables) and values.
1. Arithmetic Operators:
The PHP arithmetic operators are used with numeric values to perform common
arithmetical operations, such as addition, subtraction, multiplication etc.
Operator Name Example Result
+ Addition $x + $y Sum of $x and $y
- Subtraction $x - $y Difference of $x and $y
* Multiplication $x * $y Product of $x and $y
/ Division $x / $y Quotient of $x and $y
% Modulus $x % $y Remainder of $x divided by $y
** Exponentiation $x ** $y Result of raising $x to the $y'th power (Introduced
in PHP 5.6)

2. Assignment Operators:
Page | 41
The PHP assignment operators are used with numeric values to write a value to a variable.
Operator Name Example Description
= Equlas x=y left operand gets set to the value of the on the right
Expression
+= SumEquals x=x+y “
-= SubEquals x=x-y “
*= MultiplyEquals x=x*y “
/= DivideEquals x=x/y “
%= ModdivideEquals x = x % y “

3. PHP Increment / Decrement Operators


The PHP increment operators are used to increment a variable value by 1.
The PHP decrement operators are used to decrement a variable value by 1.
Operator Name Description
++$x $x+ Pre-increment Increments $x by one, then returns $x
+ Post-increment Returns $x, then increments $x by one
--$x Pre-decrement Decrements $x by one, then returns $x
$x-- Post-decrement Returns $x, then decrements $x by one

4. PHP Comparison Operators:


The PHP comparison operators are used to compare two values (number or string):
Operator Name Example Result
== Equal $x == $y Returns true if $x is equal to $y
=== Identical $x === $y Returns true if $x is equal to $y, and they are of the
same type
!= Not equal $x != $y Returns true if $x is not equal to $y
<> Not equal $x <> $y Returns true if $x is not equal to $y
!== Not identical $x !== $y Returns true if $x is not equal to $y, or they are not
of the same type
> Greater than $x > $y Returns true if $x is greater than $y
< Less than $x < $y Returns true if $x is less than $y
>= Greater than or $x >= $y Returns true if $x is greater than or equal to $y
equal to
<= Less than or $x <= $y Returns true if $x is less than or equal to $y
equal to

5. PHP Logical Operators:


The PHP logical operators are used to combine conditional statements.

PHP and MySQL 7 Prepared By: GiriBabu


Operator Name Example Result
And And $x and $y True if both $x and $y are true
Or Or $x or $y True if either $x or $y is true
Xor Xor $x xor $y True if either $x or $y is true, but not both
&& And $x && $y True if both $x and $y are true
Page | 42
|| Or $x || $y True if either $x or $y is true
! Not !$x True if $x is not true

6. PHP String Operators


PHP has two operators that are specially designed for strings.
Operator Name Example Result
. Concatenation $txt1 . $txt2 Concatenation of $txt1 and $txt2
.= Concatenation assignment $txt1 .= $txt2 Appends $txt2 to $txt1

7. PHP Array Operators:


The PHP array operators are used to compare arrays.
Operator Name Example Result
+ Union $x + $y Union of $x and $y
== Equality $x == $y Returns true if $x and $y have the same key/value pairs
=== Identity $x === $y Returns true if $x and $y have the same key/value pairs
in the same order and of the same types
!= Inequality $x != $y Returns true if $x is not equal to $y
<> Inequality $x <> $y Returns true if $x is not equal to $y
!== Non- $x !== $y Returns true if $x is not identical to $y
identity

Control Structures in PHP:

PHP Conditional Statements/Bracnhing control Statements/Decision Making Statements:


Conditional statements are used to perform different actions based on different conditions.
In PHP we have the following conditional statements:
 if statement - executes some code if one condition is true
 if...else statement - executes some code if a condition is true and another code if that
condition is false
 if...elseif....else statement - executes different codes for more than two conditions
 switch statement - selects one of many blocks of code to be executed

if Statement: The if statement executes some code if condition is true.


Syntax: if (condition)
{
code to be executed if condition is true;
}
The example below will output “Have a good day!” if the current time is less than 20.

PHP and MySQL 8 Prepared By: GiriBabu


Ex: <?php
$t = date(“H”);
if ($t < “20”) {
echo “Have a good day!”;
?>
The if…else Statement: Page | 43
The if….else statement executes some code if a condition is true and another code if that
condition is false.
Syntax: if (condition) {
code to be executed if condition is true;
} else {
code to be executed if condition is false;
}
The example below will output “Have a good day!” if the current time is less than 20, and “Have
a good night!” otherwise:
Ex: <?php
$t = date(“H”);
if ($t < “20”) {
echo “Have a good day!”;
} else {
echo “Have a good night!”;
}
?>
The if…elseif….else Statement:
The if....elseif...else statement executes different statements for more than two conditions.
Syntax: if (condition) {
code to be executed if this condition is true;
} elseif (condition) {
code to be executed if this condition is true;
} else {
code to be executed if all conditions are false;
}
The example below will output "Have a good morning!" if the current time is less than 10, and
"Have a good day!" if the current time is less than 20. Otherwise it will output "Have a good night!":
Example:
<?php
$t = date("H");
if ($t < "10") {
echo "Have a good morning!";
} elseif ($t < "20") {
echo "Have a good day!";
} else {
echo "Have a good night!";
}
?>

PHP and MySQL 9 Prepared By: GiriBabu


The switch Statement:
The switch statement is used to perform different actions based on different conditions. Select one
of many blocks of code to be executed.
Syntax:
switch (exp/variable)
{ Page | 44
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;
}
The value of the switch expression/variable value is 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. If no case value is
matched the default statement is used. Use break to prevent the code from running into the next case
automatically.
<?php
$favcolor = "red";
switch ($favcolor)
{
case "red": echo "Your favorite color is red!";
break;
case "blue": echo "Your favorite color is blue!";
break;
case "green": echo "Your favorite color is green!";
break;
default: echo "Your favorite color is neither red, blue, nor green!";
}
?>
PHP Loop statements:
Looping statements are used to execute single or group of statements repeatedly until the given
condition is true.
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 while Loop:


The while loop executes a block of code as long as the specified condition is true. It is entry level
loop control structure.

PHP and MySQL 10 Prepared By: GiriBabu


Syntax: while (condition is true)
{ code to be executed;
}
Ex: <?php
$x = 1;
while($x <= 5) Page | 45
{
echo "The number is: $x <br>";
$x++;
}?
>
The do...while Loop:
The do...while loop will always execute its statements at least once, even if the condition is false
the first time. The condition is tested AFTER executing the statements within the loop if it is true repeat
the loop statements. It called exit level loop control sturucture
Syntax: do {
code to be executed;
} while (condition is true);
Ex: <?php
$x = 1; //$x = 6;
do {
echo "The number is: $x <br>";
$x++;
} while ($x <= 5);
?>
The PHP for Loop:
PHP for loops execute a block of code a specified number of times. 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
The example below displays the numbers from 0 to 10:
<?php
for ($x = 0; $x <= 10; $x++)
{ echo "The number is: $x
<br>";
}?
>
PHP and MySQL 11 Prepared By: GiriBabu

Page | 46
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;
Page | 47
}
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.
Ex: <?php
$colors = array("red", "green", "blue", "yellow");
foreach ($colors as $value) {
echo "$value <br>";
}
?>

PHP Functions:
A function is a basic building block of statements that can be used repeatedly in a program to
improve re-usability. A function will be executed by a call to the function. Function contains set of
instructions enclosed by “{ }” which performs specific operation.

User Defined Functions: Besides the built-in PHP functions, we can create our own functions.
Declaration of a function:
A user-defined function declaration starts with the word function then it contains a name.
Syntax: function functionName() {
code to be executed;
}
 Calling a function: This calls the user defined function definition.
Syntax: functionname();
Ex: <?php
function disply() //fuction definition
{
echo "hello Giribabu”;
}
disply(); // call the function
?>
PHP Function Arguments:
Information can be passed from calling function to called function 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.
The following example has a function with one argument ($fname). When the disply() function is
called, we also pass along a name, and the name is used inside the function, which output wish the name.
<?php
function disply ($name)

PHP and MySQL 12 Prepared By: GiriBabu


{
echo "hello:$name";
}
disply("Giribabu");
?>
Page | 48
The following example has a function with two arguments ($fname and $year):

<?php
function disply ($name,$year)
{
echo "hello:$name this year is : $year";
}
disply("Giribabu","2018");
?>
PHP Default Argument Value:
If we call the function without arguments it takes the default value as argument:
<?php
function disply ($name,$year=2015)
{
echo "hello:$name this year is : $year";
}
disply("Giribabu","2018");
disply("Giribabu");
?>
Functions returning values:
A function returns a value from called fuction to calling function after execution of that by using
the return statement:
<?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);
?>

PHP 5 Arrays:

An array is a special variable, which can hold more than one value at a time. An array can hold
many values under a single name, and you can access the values by referring to an index number.
In PHP, there are three types of arrays:
Indexed arrays - Arrays with a numeric index
Associative arrays - Arrays with named keys

PHP and MySQL 13 Prepared By: GiriBabu


Multidimensional arrays - Arrays containing one or more arrays
Create an Array in PHP:
In PHP, the array() function is used to create an array:
array();
PHP Indexed Arrays:
There are two ways to create indexed arrays: Page | 49
The index can be assigned automatically its values are always starts at 0.
The Example creates an indexed array named $cars, assigns three elements to it
$cars = array("Volvo", "BMW", "Toyota");
or the index can be assigned manually:
$cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota";
Prints a text containing the array values:
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[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";
The named keys can then be used in a script:
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
echo "Peter is " . $age['Peter'] . " years old.";
?>
To print all the values of an associative array, you could use a foreach loop, like this:
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
foreach($age as $x => $x_value) {
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}?
>

PHP 5 Multidimensional Arrays:


A multidimensional array is an array containing one or more arrays. However, arrays more than
three levels deep are hard to manage for most people.
The dimension of an array indicates the number of indices you need to select an element.

PHP and MySQL 14 Prepared By: GiriBabu


 For a two-dimensional array you need two indices to select an element
 For a three-dimensional array you need three indices to select an element
Two-dimensional Arrays:
A two-dimensional array is an array of arrays; a three-dimensional array is an array of arrays of
arrays).
Page | 50
First, take a look at the following table:
Name Stock Sold
Volvo 22 18
BMW 15 13
Saab 5 2
Land Rover 17 15
We can store the data from the table above in a two-dimensional array, like this:
$cars = array
( array("Volvo",22,18
),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);
Now the two-dimensional $cars array contains four arrays, and it has two indices: row and
column.
To get access to the elements of the $cars array we must point to the two indices (row and column):
<?php
echo $cars[0][0].": In stock: ".$cars[0][1].", sold: ".$cars[0][2].".<br>";
echo $cars[1][0].": In stock: ".$cars[1][1].", sold: ".$cars[1][2].".<br>";
echo $cars[2][0].": In stock: ".$cars[2][1].", sold: ".$cars[2][2].".<br>";
echo $cars[3][0].": In stock: ".$cars[3][1].", sold: ".$cars[3][2].".<br>";
?>
We can also put a for loop inside another for loop to get the elements of the $cars array.
<?php
for ($row = 0; $row < 4; $row++) {
echo "<p><b>Row number $row</b></p>";
echo "<ul>";
for ($col = 0; $col < 3; $col++) {
echo "<li>".$cars[$row][$col]."</li>";
}
echo
"</ul>"; }
?>
Functions for Arrays:
The elements in an array can be sorted in alphabetical or numerical order, descending or
ascending.

PHP and MySQL 15 Prepared By: GiriBabu


1. count (): The count() function is used to return the length as number of elements of an array.
Ex: <?php
$cars = array("Volvo", "BMW", "Toyota");
$arrlength = count($cars);
for($x = 0; $x < $arrlength; $x++) {
echo $cars[$x]; Page | 51
echo “<br>”;
}
?>
2. sort() : the sort() function arranges elements in an array in ascending order
Ex: Alphabetical order sorting:
<?php
$cars = array("Volvo", "BMW", "Toyota");
sort($cars);
?>
Number sorting:
<?php
$numbers = array(4, 6, 2, 22, 11);
sort($numbers);
?>
3. rsort() : the sort() function arranges elements in an array in descending order
Ex: Descending Alphabetical order:
<?php
$cars = array("Volvo", "BMW", "Toyota");
rsort($cars);
?>
Descending numerical order:
<?php
$numbers = array(4, 6, 2, 22, 11);
rsort($numbers);
?>
4. asort(): It sorts the elements in an associative array in ascending order.
Ex: <?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
asort($age);
?>
5. arsort(): It sorts the elements in an associative array in descending order.
Ex: <?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
arsort($age);
?>
6. array_pop(): Delete the last element of an array:
<?php
$a=array("red","green","blue");

PHP and MySQL 16 Prepared By: GiriBabu


array_pop($a);
print_r($a);
?>
7. array_push():Insert new elements in to the end of an array:
<?php
Page | 52
$a=array("red","green");
array_push($a,"blue","yellow");
print_r($a);
?>
8. array_search(): This function search an array for a value and returns the key.
Search an array for the value "red" and return its key:
<?php
$a=array("a"=>"red","b"=>"green","c"=>"blue");
echo array_search("red",$a);
?>
9. array_sum(): The array_sum() function returns the sum of all the values in the array.
Return the sum of all the values in the array (5+15+25):
<?php
$a=array(5,15,25);
echo array_sum($a);
?>
10. array_unique(): This function removes duplicate values from an array. If two or more array
values are the same, the first appearance will be kept and the other will be removed.
<?php
$a=array("a"=>"red","b"=>"green","c"=>"red");
print_r(array_unique($a));
?>
11. array_product(): This function calculates and returns the product of an array.
<?php
$a=array(5,5);
echo(array_product($a));
?>
12. array_merge(): This function merges one or more arrays into one array.
<?php
$a1=array("red","green");
$a2=array("blue","yellow");
print_r(array_merge($a1,$a2));
13. array_diff(): This function compares the values of two (or more) arrays, and returns the
differences.
<?php
$a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
$a2=array("e"=>"red","f"=>"green","g"=>"blue");
$result=array_diff($a1,$a2);

PHP and MySQL 17 Prepared By: GiriBabu


print_r($result);
?>

PHP String Functions:


Strings are nothing but array of characters. Strings are always enclosed by double quotes or single
quotes. String functions commonly used to manipulate strings. Page | 53

1. strlen() : The PHP strlen() function returns the length of a string.


<?php
echo strlen("Hello world!"); // outputs 12
?>
2. str_word_count(): Count The Number of Words in a String
<?php
echo str_word_count("Hello world!"); // outputs 2
?>
3. strrev(): The PHP strrev() function reverses a string:
<?php
echo strrev("Hello world!"); // outputs !dlrow olleH
?>
4. strpos() : 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.
<?php
echo strpos("Hello world!", "world"); // outputs 6
?>
5. str_replace(): The PHP str_replace() function replaces some characters with some other
characters in a string.
<?php
echo str_replace("world", "Dolly", "Hello world!"); // outputs Hello Dolly!
?>
PHP Date and Time:
These functions allow you to get the date and time from the server where your PHP scripts are
running.
Syntax: date(format,timestamp)
Parameter Description
format Required. Specifies the format of the timestamp
timestamp Optional. Specifies a timestamp. Default is the current date and time
A timestamp is a sequence of characters, denoting the date and/or time at which a certain event
occurred.
The required format parameter of the date() function specifies how to format the date (or time).
Here are some characters that are commonly used for dates:
d - Represents the day of the month (01 to 31)
m - Represents a month (01 to 12)
Y - Represents a year (in four digits)

PHP and MySQL 18 Prepared By: GiriBabu


l (lowercase 'L') - Represents the day of the week
Other characters, like"/", ".", or "-" can also be inserted between the characters to add additional
formatting.
The example below formats today's date in three different ways:
<?php
Page | 54
echo "Today is " . date("Y/m/d") . "<br>";
echo "Today is " . date("Y.m.d") . "<br>";
echo "Today is " . date("Y-m-d") . "<br>";
echo "Today is " . date("l");
?>

Checkdate(): This function checks the validity of the date formed by the arguments.

Syn: checkdate ( $month, $day, $year );

The year is between 1 and 32767 inclusive. The month is between 1 and 12 inclusive. The day is
within the allowed number of days for the given month.

<?php
var_dump(checkdate(12, 1, 1990));
print "\n" ;
var_dump(checkdate(23, 29, 2011));
?>

getdate(): It returns an associative array of information related to the typestamp. The


returning array contains ten elements with relevant information needed when formatting a date string −

[seconds] − seconds
[minutes] − minutes
[hours] − hours
[mday] − day of the month
[wday] − day of the week
[year] − year
[yday] − day of the year
[weekday] − name of the weekday
[month] − name of the month
<?php
$today = getdate();
print_r($today);
?>

PHP and MySQL 19 Prepared By: GiriBabu


Unit IV
Syllabus: Forms: Creating forms, Accessing form input with user defined arrays, hidden
fields, Redirecting a form after submission, mail, File uploads.
Cookies and Session: Introduction to cookies, setting cookie with PHP, Session
function, start session, working with session variables. destroy session. Page | 55

I. INTRODUCTION TO FORMS:
Dynamic websites provide the functionalities that can use to store, update, retrieve, and delete
the data in a database while creating these websites we use forms. A form is a document that containing
black fields, that can be filled by the user with data or select the data. Casually the data will store in the
data base
II. HOW TO CREATE A INTERACTIVE FORM IN PHP?
The HTML <form> element defines a form that is used to collect user input. Form elements are
different types of input elements, like text fields, checkboxes, radio buttons, submit buttons, and more.
The <input> Element:
The <input> element is the most important form element.
The <input> element can be displayed in several ways, depending on the type attribute.
Here are some examples:-
<input type="text"> : Defines a one-line text input field. The default width of a text field
is 20 characters.
<input type="radio"> : Defines a radio button (for selecting one of many choices)
<input type="submit">: Defines a submit button (for submitting the form)
III. WHAT ARE ATTRIBUTES FOR FORM TAG?
The Name Attribute:
Each input field must have a name attribute to be submitted. If the name attribute is omitted, the
data of that input field will not be sent at all.
Example form:
<form>
<input type="text" name="firstname"><br>
<input type="radio" name="gender" value="male" checked> Male<br>
<input type="radio" name="gender" value="female"> Female<br>
<input type="submit" value="Submit">
</form>
The Action Attribute:
The action attribute of the <form> element defines the action to be performed when the form is
submitted. Normally, the form data is sent to a web page on the server when the user clicks on the
submit button.

Web Technologies Prepared By: Giribabu


In the example above, the form data is sent to a page on the server called "/action_page.php".
This page contains a server-side script that handles the form data:
<form action="/action_page.php">
If the action attribute is omitted, the action is set to the current page. Page | 56
The Target Attribute
The target attribute specifies if the submitted result will open in a new browser tab, a frame, or in
the current window.
The default value is "_self" which means the form will be submitted in the current window. To
make the form result open in a new browser tab, use the value "_blank":
Example: <form action="/action_page.php" target="_blank">
Other legal values are "_parent", "_top", or a name representing the name of an iframe.
The Method Attribute:
The method attribute specifies the HTTP method (GET or POST) to be used when submitting
the form data:
Example: <form action="/action_page.php" method="get">
Example: <form action="/action_page.php" method="post">
GET & POST Methods:
There are two ways the browser client can send information to the web server.
The GET Method
The POST Method
Before the browser sends the information, it encodes it using a scheme called URL encoding. In
this scheme, name/value pairs are joined with equal signs and different pairs are separated by the
ampersand.
name1=value1&name2=value2&name3=value3
Spaces are removed and replaced with the + character and any other non alphanumeric
characters are replaced with a hexadecimal values. After the information is encoded it is sent to the
server.
The GET Method
The default method when submitting form data is GET. However, when GET is used, the
submitted form data (encoded user information) will be visible in the page address field. The page
address and the encoded information are separated by the ?character.
Ex: http://www.test.com/index.htm?name1=value1&name2=value2
Ex: http://www.test.com/index.htm?firstname=Mickey&lastname=Mouse
The GET method appended form-data into the URL in name/value pairs. It is restricted to send
upto 1024 characters only. Never use GET method if you have password or other sensitive information
to be sent to the server. GET can't be used to send binary data, like images or word documents, to the

Web Technologies Prepared By: Giribabu


server. Useful for form submissions where a user wants to bookmark the result. GET is better for non-
secure data.
The PHP provides $_GET[ ] associative array to access all the sent information using GET
method. Page | 57
Ex: Input.html
<html>
<body>
<form action = "test.php" method = "GET">
Name: <input type = "text" name = "name" />
Age: <input type = "text" name = "age" />
<input type = "submit" />
</form>
</body>
</html>
test.php script:
<?php
echo "Welcome ". $_GET['name']. "<br />";
echo "You are ". $_GET['age']. " years old.";
?>
The POST Method:
The POST method does not display the submitted form data in the page address field. The data
sent by POST method goes through HTTP header so security depends on HTTP protocol. By using
Secure HTTP you can make sure that your information is secure.
The POST method does not have any restriction on data size to be sent. The POST method can
be used to send ASCII as well as binary data.
The PHP provides $_POST associative array to access all the sent information using POST
method.
Input.html
<html>
<body>
<form action = "test.php" method = "POST">
Name: <input type = "text" name = "name" />
Age: <input type = "text" name = "age" />
<input type = "submit" />
</form>
</body>
</html>
Web Technologies Prepared By: Giribabu
test.php script:
<?php
echo "Welcome ". $_POST['name']. "<br />";
echo "You are ". $_POST['age']. " years old."; Page | 58
?>
The $_REQUEST variable:
The PHP $_REQUEST variable can be used to get the result from form data sent with both the
GET and POST methods.
Ex: test.php script:
<?php
echo "Welcome ". $_REQUEST['name']. "<br />";
echo "You are ". $_REQUEST ['age']. " years old.";
?>
IV. HOW TO ACCESS FORM INPUT WITH USER-DEFINED ARRAYS?
When we working with form SELECT element. These element make it possible for the user to
choose multiple items.
Ex: <select name="products" multiple>
The script that receives this data has access to receive multiple values corresponding to this
name. We can change this behaviour by renaming an element of this kind so that its name ends with an
empty set of square brackets.
Ex: An HTML Form Including a SELECT Element
<html>
<head>
<title> Form Including a SELECT Element </title>
</head>
<body>
<form action="input.php" method="POST">
Name: <input type="text" name="user"> <br>
Address: <textarea name="address" rows="5" cols="40"></textarea> <br>
Pick Products: <br> <select name="products[]" multiple>
<option>AC</option>
<option>Washing Mechine</option>
<option>TV</option>
<option>Refrigerator</option>
</select>
<br><br>
<input type="submit" value="hit it!">
Web Technologies Prepared By: Giribabu
</form>
</body>
</html>
The PHP script that processes the form input, we find that input from the "products[]" form
Page | 59
element created is available in an array called $_POST[products]. Because products[] is a SELECT
element, we offer the user multiple choices using the option elements.

Input.Php:

<html>
<head>
<title> Reading input from the form </title>
</head>
<body>
<?php
print "Welcome <b>$_POST[user]</b><p>\n\n";
print "Your address is:<p>\n\n<b>$_POST[address]</b><p>\n\n";
print "Your product choices are:<p>\n\n";
print "</ul>";
foreach ($_POST[products] as $value)
{
print "<li>$value\n";
}
print "</ul>";
?>
</body>
</html>

Ex: An HTML Form Including a Check Box Element:

Although the looping technique is particularly useful with the SELECT element, it also works
with enables a user to choose many values within a single field name. As long as the name you choose
ends with empty square brackets, PHP compiles the user input for this field into an array.
Select Product:
<input type="checkbox" name="products[]" value="AC">AC<br>
<input type="checkbox" name="products[]" value="Washing Mechine"> Washing Mechine <br>
<input type="checkbox" name="products[]" value="TV"> TV <br>
<input type="checkbox" name="products[]" value="Refregirator"> Refregirator"<br>

Web Technologies Prepared By: Giribabu


V. WHAT IS HIDDEN FIELD IN PHP?
The hidden value of input type defines a form field that is include data that cannot be seen or
modified by users when a form is submitted. When the user submits the form, all of the data they have
entered is sent, including the data stored invisibly in the hidden fields. Page | 60
Note: While the value is not displayed to the user in the page's content, it is visible (and can be
edited) using any browser's developer tools or "View Source" functionality.
Ex: <input type="hidden" id="custId" name="custId" value="3487">
Program:
<html>
<body>
<h1>Define a hidden input field:</h1>
<form action="/action_page.php">
First name: <input type="text" name="fname"><br>
<input type="hidden" id="custId" name="custId" value="3487">
<input type="submit" value="Submit">
</form>
</body>
</html>

VI. HOW TO REDIRECTING A FORM AFTER SUBMISSION?


In PHP redirection is done by using header() function as it is considered to be the fastest method
to redirect traffic from one web page to another. The main advantage of this method is that it can
navigate from one location to another without the user having to click on a link or button.
inputform.html <!
DOCTYPE html>
<html>
<head>
<title>Redirect Form To a Particular Page On Submit - Demo Preview</title>
</head>
<body>
<h2>Redirect Form To a Particular Page On Submit using PHP</h2>
<form action="redirect_form.php" method="post">
<label>Name :</label><input type='text' name="name" >
<label>Email :</label><input type='text' name="email">
<label>Contact :</label><input type='text' name="contact">
<label>Address:</label><input type='text' name="address">
<input name="submit" type='submit' value='Submit'>
Web Technologies Prepared By: Giribabu
</form>
</body>
</html>
redirect_form.php Page | 61
<!---- Including PHP File Here ---->
<?php
include "redirect.php";
?>
redirect.php:
<?php
if(isset($_POST['submit']))
{
// Fetching variables of the form which travels in URL
$name = $_POST['name'];
$email = $_POST['email'];
$contact = $_POST['contact'];
$address = $_POST['address'];
if($name !=''&& $email !=''&& $contact !=''&& $address !='')
{
// To redirect form on a particular page
header("Location: https://www.google.co.in");
}
else
{
echo "Please fill all
fields..."; }
}?
>

VI. HOW TO SEND MAILS WITH PHP SCRIPT:


The mail() function allows you to send emails directly from a script.
Syntax: mail(to, subject, message, headers);
Parameter Description
To Required. Specifies the receiver / receivers of the email
Ex: $to = "[email protected]";
Subject Required. Specifies the subject of the email.
Note: This parameter cannot contain any newline characters.
Ex: $subject = "My subject";

Web Technologies Prepared By: Giribabu


message Required. Defines the message to be sent. Each line should be separated with a
LF (\n). Lines should not exceed 70 characters.
Ex: $txt = "Hello world!";
Headers Optional. Specifies additional headers, like From, Cc, and Bcc. The additional
Page | 62
headers should be separated with a CRLF (\r\n).
Note: When sending an email, it must contain a From header. This can be set with this
parameter or in the php.ini file.
Ex: $headers = "From: [email protected]"."\r\
n"."CC: somebody [email protected]";

Runtime Configuration:
The behaviour of the mail functions is affected by settings in php.ini.
Name Default Description Changeable
mail.add_x_header "0" Add X-PHP-Originating-Script that will PHP_INI_PERDIR
include UID of the script followed by the
filename. For PHP 5.3.0 and above
mail.log NULL The path to a log file that will log all mail() PHP_INI_PERDIR
calls. Log include full path of script, line
number, To address and headers. For PHP
5.3.0 and above
SMTP "localhost" Windows only: The DNS name or IP address PHP_INI_ALL
of the SMTP server
smtp_port "25" Windows only: The SMTP port number. For PHP_INI_ALL
PHP 4.3.0 and above
sendmail_from NULL Windows only: Specifies the "from" address PHP_INI_ALL
to be used when sending mail from mail()
sendmail_path "/usr/sbin/se Specifies where the sendmail program can be PHP_INI_SYSTEM
ndmail -t -i" found. This directive works also under
Windows. If set, SMTP, smtp_port and
sendmail_from are ignored
Ex: Send an email with extra headers.
<?php
$to = "[email protected]";
$subject = "My subject";
$txt = "Hello world!";
$headers = "From: [email protected]" . "\r\n" ."CC: [email protected]";

Web Technologies Prepared By: Giribabu


mail($to,$subject,$txt,$headers);
?>
VII. HOW TO UPLOAD FILES IN PHP SCRIPT:
A PHP script can be used with a HTML form to allow users to upload files to the server. Initially
Page | 63
files are uploaded into a temporary directory and then relocated to a target destination by a PHP script.

The process of uploading a file follows these steps −


The user opens the page containing a HTML form featuring a text files, a browse button and a
submit button.
 The user clicks the browse button and selects a file to upload from the local PC.
 The full path to the selected file appears in the text filed then the user clicks the submit button.
 The selected file is sent to the temporary directory on the server.
 The PHP script that was specified as the form handler in the form's action attribute checks that
the file has arrived and then copies the file into an intended directory.
 The PHP script confirms the success to the user.
 As usual when writing files it is necessary for both temporary and final locations to have
permissions set that enable file writing. If either is set to be read-only then process will fail.
 An uploaded file could be a text file or image file or any document.
Creating an upload script:
There is one global PHP variable called $_FILES. This variable is an associate double
dimension array and keeps all the information related to uploaded file. So if the value assigned to
the input's name attribute in uploading form was file, then PHP would create following five
variables −
1. $_FILES['file']['tmp_name'] − the uploaded file in the temporary directory on the web server.
2. $_FILES['file']['name'] − the actual name of the uploaded file.
3. $_FILES['file']['size'] − the size in bytes of the uploaded file.
4. $_FILES['file']['type'] − the MIME type of the uploaded file.
5. $_FILES['file']['error'] − the error code associated with this file upload.
is_uploaded_file():
By using this function we can check whether the file is uploaded from client system ro server
temporarily location or not.
Syn: is_uploaded_file($_files['filename']['tmp_name']);
move_uploaded_file():
By using this we can move the uploaded file from temporary location to permanent location. It
contains 2 arguments temporary filename and permanent location path.
Syn: move_uploaded_file($_files['filename']['tmp_name'],"path of the location");

Web Technologies Prepared By: Giribabu


MIME Type:
MIME stands for Multipurpose Internet Mail Extension. It is a type of extension used to transfer
the files from one location to other location after user click the Submit button.
When you creates an up loaded form. This form is having "method attribute set to post" and
Page | 64
"enctype attribute used to specify the type of input file" is set to multipart/form-data
By default Form can transfer text format HTML data. If you want to transfer another format file
we need to specify MIME type of that file.
Some of the MIME types are:
exe: Executable files/applications/octant stream
jpg: Image/JPEG files
pdf: application/pdf
mupltipart/form-data: it supports any type of data.

Ex: Program for uploading an image file.


upload.html
<html>
<body>
<form action="" method="POST" enctype="multipart/form-data">
<input type="file" name="image" />
<input type="submit"/>
</form>
</body>
</html>

fileupload.php
<?php
if(isset($_FILES['image']))
{
$errors= array();
$file_name = $_FILES['image']['name'];
$file_size =$_FILES['image']['size'];
$file_tmp =$_FILES['image']['tmp_name'];
$file_type=$_FILES['image']['type'];
if(is_uploaded_file($_FILES['image']['tmp_name']))
{
$fname=$_Files['image']['name'];
if(move_uploaded_file($_Files['image']['tmp_name'],"uploads/$fname"))
Web Technologies Prepared By: Giribabu
echo "file is moved";
else
echno "not moved fie";
} Page | 65

Example:
Below example should allow upload images and gives back result as uploaded file information.
<?php
if(isset($_FILES['image']))
{
$errors= array();
$file_name = $_FILES['image']['name'];
$file_size = $_FILES['image']['size'];
$file_tmp = $_FILES['image']['tmp_name'];
$file_type = $_FILES['image']['type'];
$file_ext=strtolower(end(explode('.',$_FILES['image']['name'])));
$expensions= array("jpeg","jpg","png"); if(in_array($file_ext,
$expensions)=== false)
{
$errors[]="extension not allowed, please choose a JPEG or PNG file.";
}
if($file_size > 2097152)
{
$errors[]='File size must be excately 2 MB';
}
if(empty($errors)==true)
{
move_uploaded_file($file_tmp,"images/".$file_name);
echo "Success";
}
else
{
print_r($errors);
}
}?
>
<html>
Web Technologies Prepared By: Giribabu
<body>
<form action = "" method = "POST" enctype = "multipart/form-data">
<input type = "file" name = "image" />
<input type = "submit"/> Page | 66
<ul>
<li>Sent file: <?php echo $_FILES['image']['name']; ?>
<li>File size: <?php echo $_FILES['image']['size']; ?>
<li>File type: <?php echo $_FILES['image']['type'] ?>
</ul>
</form>
</body>
</html>

VIII. WHAT IS COOKIE IN PHP? HOW TO CREATE AND DELETE COOKIE?


Cookies are text files that the server embeds on the client computer. It is often used to identify a
user each time the same computer requests a page with a browser, it will send the cookie too. Cookies
are usually set in an HTTP header
There are three steps involved in identifying returning users −
a) Server script sends a set of cookies to the browser.
For example name, age, or identification number etc.
b) Browser stores this information on local machine for future use.
c) When next time browser sends any request to web server then it sends those cookies information
to the server and server uses that information to identify the user.
Cookies store the information in 2 locations either Harddisc or RAM of client system.
1. In memory Cookie:
If we create any cookie without explicit expiry tag comes under inmemory cookie.
Inmemory cookie stores the information in clients RAM memory location and destroys the data
when user closed the browser.
2. Persistence Cookie:
If we create any cookie with explicit expiry tag comes under persistence cookie.
Persistence cookie stores the data in hard disk and deletes the information when the lifetime
cookie completed.
Create Cookies With PHP:
PHP provided setcookie() function to set a cookie. This function requires upto six arguments and
should be called before <html> tag. For each cookie this function has to be called separately.
setcookie(name, value, expire, path, domain, security);
Only the name parameter is required. All other parameters are optional.
Web Technologies Prepared By: Giribabu
Here is the detail of all the arguments −
 Name − This sets the name of the cookie and is stored in an environment variable called
HTTP_COOKIE_VARS. This variable is used while accessing cookies.
 Value − This sets the value of the named variable and is the content that you actually want to Page | 67
store.
 Expiry − This specify a future time in seconds since 00:00:00 GMT on 1st Jan 1970. After this
time cookie will become inaccessible. If this parameter is not set then cookie will automatically
expire when the Web Browser is closed.
 Path − This specifies the directories for which the cookie is valid. A single forward slash
character permits the cookie to be valid for all directories.
 Domain − This can be used to specify the domain name in very large domains and must contain
at least two periods to be valid. All cookies are only valid for the host and domain which
created them.
 Security − This can be set to 1 to specify that the cookie should only be sent by secure
transmission using HTTPS otherwise set to 0 which mean cookie can be sent by regular HTTP.
Following example will create two cookies name and age these cookies will be expired after
one hour.
<?php
setcookie("name", "John", time()+3600, "/","", 0);
setcookie("age", "36", time()+3600, "/", "", 0);
?>
<html>
<head>
<title>Setting Cookies with PHP</title>
</head>
<body>
<?php echo "Set Cookies"?>
</body>
</html>
Accessing Cookies with P
HP
PHP provides many ways to access cookies. Simplest way is to use either $_COOKIE or
$HTTP_COOKIE_VARS variables. Following example will access all the cookies set in above
example.
<html>
<head>
<title>Accessing Cookies with PHP</title>
</head>
Web Technologies Prepared By: Giribabu

Page | 68
<body>
<?php
echo $_COOKIE["name"]. "<br />";
/* is equivalent to */ Page | 69
echo $HTTP_COOKIE_VARS["name"]. "<br />";
echo $_COOKIE["age"] . "<br />";
/* is equivalent to */
echo $HTTP_COOKIE_VARS["age"] . "<br />";
?>
</body>
</html>
Note: You can use isset() function to check if a cookie is set or not.
<html>
<head>
<title>Accessing Cookies with PHP</title>
</head>

<body>
<?php
if( isset($_COOKIE["name"]))
echo "Welcome " . $_COOKIE["name"] . "<br />";
else
echo "Sorry... Not recognized" . "<br />";
?>
</body>
</html>
Deleting Cookie with PHP
Officially, to delete a cookie you should call setcookie() with the name argument only but this
does not always work well, however, and should not be relied on.
It is safest to set the cookie with a date that has already expired −
Delete a Cookie
To delete a cookie, use the setcookie() function with an expiration date in the past:
Example
<?php
// set the expiration date to one hour ago
setcookie("name", "", time() - 3600);

Web Technologies Prepared By: Giribabu


setcookie("age", "", time() - 3600);
?>
<html>
<body> Page | 70
<?php
echo "Cookie name and age are deleted.";
?>
</body>
</html>
IX. WHAT IS A SESSION? HOW TO START AND DESTROY SESSIONS IN PHP?
A user can work with an application, they open it, do some changes, and then you close it. This
is much like a Session. The personal computer knows who you are. It knows when you start the
application and when you end. But on the internet the main problem is the web server does not know
who you are or what you do, because the HTTP address doesn't maintain state.
A session solve this problem by creates a file in a temporary directory on the server where
registered session variables and their values are stored about one single user. This data will be available
to all pages on the site during that visit. By Default, session variables last until the user closes the
browser.
Starting a PHP Session:
A PHP session is easily started by making a call to the session_start() function. This function
first checks if a session is already started and if none is started then it starts one. so
The session_start() function must be the very first thing in your document before any HTML tags.
Put this code in a test.php file and load this file many times to see the result −
<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Set session variables
$_SESSION["favcolor"] = "pink";
$_SESSION["favanimal"] = "cow";
echo "Session variables are set."; ?
>

Web Technologies
</body>
</html>

Working with Session Variables: Page | 71


Session variables are not passed individually to each new page, instead they are retrieved from
the session we open at the beginning of each page (session_start()).
Session variables are stored in associative array called $_SESSION[]. These variables can be
accessed during lifetime of a session.
Make use of isset() function to check if session variable is already set or not.
<?php
// Set session variables
$_SESSION["favcolor"] = "pink";
$_SESSION["favanimal"] = "cow";
if( isset( $_SESSION['favanimal'] ) )
{
echo "Session variables are
set."; }
else
{
echo "Session variables are not
set."; }
?>
To show all the session variable values for a user session by using the global $_SESSION variable:
Ex: <?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
print_r($_SESSION);
?>
</body>
</html>
Destroying a PHP Session:

Web Technologies
A PHP session can be destroyed by session_destroy() function. This function does not need any
argument and a single call can destroy all the session variables. If you want to destroy a single session
variable then you can use unset() function to unset a session variable.
Ex: Here is the example to unset a single variable − Page | 72
<?php
unset($_SESSION["favcolor"]
?>
Ex: Here is the call which will destroy all the session variables −
<?php
session_destroy();
?>
Ex:- The following example starts a session then register a variable called counter that is incremented
each time the page is visited during the session.
<?php
session_start();
if( isset( $_SESSION['counter'] ) )
{
$_SESSION['counter'] += 1;
}
else
{
$_SESSION['counter'] = 1;
}
$msg = "You have visited this page ". $_SESSION['counter'];
$msg .= "in this session.";
?>
<html>
<head>
<title>Setting up a PHP session</title>
</head>
<body> <?
php
echo ( $msg );
?>
</body>
</html>

Difference between Cookies and Sessions:


Cookies Sessions
1. Cookies stores the information in client system. 1. Sever stores the data in Server_system.
2. Cookies stores limited amount of data. 2. Sessions stores huge amount of data.
3. Cookies can stores only text data. 3. Sessions can stores any type of data
4. Cookies are unsecured 4. Sessions are highly secured

Web Technologies
Unit V
SYLLABUS: Files and directories: create and delete files, opening file for writing, reading
or appending. Writing or appending to file. Working with directories, Building a text editor, File
Uploading & Downloading. Page | 73

MySQL and PHP: interacting with MySQL using PHP, Performing basic database
operations, (DML) (Insert, Delete, Update, Select), Setting query parameter, Working with Data.

MySQL
What is a Database?
A database is a separate application that stores a collection of data. Each database has one or
more distinct APIs for creating, accessing, managing, searching and replicating the data it holds.
Other kinds of data stores can also be used, such as files on the file system or large hash tables
in memory but data fetching and writing would not be so fast and easy with those type of systems.
Nowadays, we use relational database management systems to store and manage huge volume
of data. This is called relational database because all the data is stored into different tables and
relations are established using primary keys or other keys known as Foreign Keys.

Data Base Terminology:


Database : A database is a collection of tables, with related data.
Table : A table is a matrix(rows and coloumn) with data. A table in a database looks
like a simple spreadsheet.
Column : One column contains data of one and the same kind.
for example: the column empname.
Row : A row is a group of related data.
for example: the data of one employ details.
Redundancy : Storing data twice, redundantly to make the system faster.
Primary Key : A primary key is unique. A key value cannot occur twice in one table. With
a key, you can only find one row.
Foreign Key : A foreign key is the linking pin between two tables.

MySQL Database:
MySQL is a fast, easy-to-use RDBMS being used for many small and big businesses. MySQL
is developed, marketed and supported by MySQL AB, which is a Swedish company. MySQL is
becoming so popular because of many good reasons −
 MySQL is released under an open-source license. So you have nothing to pay to use it.
 MySQL works on many operating systems and with many languages including PHP, PERL, C,
C++, JAVA, etc.
 MySQL works very quickly and works well even with large data sets.
 Page | 74
MySQL supports large databases, up to 50 million rows or more in a table. The default file size
limit for a table is 4GB, but you can increase this (if your operating system can handle it) to a
theoretical limit of 8 million terabytes (TB).
 MySQL is customizable. The open-source GPL license allows programmers to modify the
MySQL software to fit their own specific environments.

Administrative MySQL Command


The list of commands which you will use to work with MySQL database:
CREATE Databasename: This will be used to create a database in the MySQL workarea.
USE Databasename : This will be used to select a database in the MySQL workarea.
SHOW DATABASES : Lists out the databases that are accessible by the MySQL DBMS.
SHOW TABLES : Shows the tables in the database once a database has been selected with
the use command.
SHOW COLUMNS FROM tablename: Shows the attributes, types of attributes, key information,
whether NULL is permitted, defaults, and other information for a table.

MySQL - PHP
Interacting with MySQL using PHP:
MySQL works very well in combination of various programming languages like PERL, C,
C++, JAVA and PHP. Out of these languages, PHP is the most popular one because of its web
application development capabilities.
PHP provides various functions to access the MySQL database and to manipulate the data
records inside the MySQL database. You would require to call the PHP functions in the same way
you call any other PHP function.

MySQL DataTypes:
A data type defines what kind of value a column can hold: integer data, character data, date and
time data, binary strings, and so on. Each column in a database table is required to have a name and a
data type. An MySQL developer must decide what type of data that will be stored inside each column
when creating a table.
Note: Data types might have different names in different database. And even if the name is the same,
the size and other details may be different.
In MySQL there are three main data types: text, number, and date.
1. Text data types:
Data type Description
CHAR(size) Holds a fixed length string (can contain letters, numbers, and special
characters). The fixed size is specified in parenthesis. Can store up to 255 Page | 75

characters
VARCHAR(size) Same as CHAR data type but difference is it Holds a variable length string.
Note: If you put a greater value than 255 it will be converted to a TEXT
type
TEXT Holds a string with a maximum length of 65,535 characters
BLOB For BLOBs (Binary Large OBjects). Holds up to 65,535 bytes of data
MEDIUMTEXT Holds a string with a maximum length of 16,777,215 characters
MEDIUMBLOB For BLOBs (Binary Large OBjects). Holds up to 16,777,215 bytes of data
LONGTEXT Holds a string with a maximum length of 4,294,967,295 characters
LONGBLOB For BLOBs (Binary Large OBjects). Holds up to 4,294,967,295 bytes of
data
ENUM(x,y,z,etc.) Let you enter a list of possible values. You can list up to 65535 values in an
ENUM list. If a value is inserted that is not in the list, a blank value will be
inserted.
Note: The values are sorted in the order you enter them.
You enter the possible values in this format: ENUM('X','Y','Z')
SET Similar to ENUM except that SET may contain up to 64 list items and can
store more than one choice

Number data types:


Data type Description
TINYINT(size) -128 to 127 normal. 0 to 255 UNSIGNED*. The maximum number of digits
may be specified in parenthesis
SMALLINT(size) -32768 to 32767 normal. 0 to 65535 UNSIGNED*. The maximum number of
digits may be specified in parenthesis
MEDIUMINT(size) -8388608 to 8388607 normal. 0 to 16777215 UNSIGNED*. The maximum
number of digits may be specified in parenthesis
INT(size) -2147483648 to 2147483647 normal. 0 to 4294967295 UNSIGNED*. The
maximum number of digits may be specified in parenthesis
BIGINT(size) -9223372036854775808 to 9223372036854775807 normal. 0 to
18446744073709551615 UNSIGNED*. The maximum number of digits may
be specified in parenthesis
FLOAT(size,d) A small number with a floating decimal point. The maximum number of digits
may be specified in the size parameter. The maximum number of digits to the
right of the decimal point is specified in the d parameter Page | 76

DOUBLE(size,d) A large number with a floating decimal point. The maximum number of digits
may be specified in the size parameter. The maximum number of digits to the
right of the decimal point is specified in the d parameter
DECIMAL(size,d) A DOUBLE stored as a string , allowing for a fixed decimal point. The
maximum number of digits may be specified in the size parameter. The
maximum number of digits to the right of the decimal point is specified in the
d parameter
*The integer types have an extra option called UNSIGNED. Normally, the integer goes from an
negative to positive value. Adding the UNSIGNED attribute will move that range up so it starts at zero
instead of a negative number.

Date data types:


Data type Description
DATE() A date. Format: YYYY-MM-DD
Note: The supported range is from '1000-01-01' to '9999-12-31'
DATETIME() *A date and time combination. Format: YYYY-MM-DD HH:MI:SS
Note: The supported range is from '1000-01-01 00:00:00' to '9999-12-31 23:59:59'
TIMESTAMP() *A timestamp. TIMESTAMP values are stored as the number of seconds since the
Unix epoch ('1970-01-01 00:00:00' UTC). Format: YYYY-MM-DD HH:MI:SS
Note: The supported range is from '1970-01-01 00:00:01' UTC to '2038-01-09
03:14:07' UTC
TIME() A time. Format: HH:MI:SS
Note: The supported range is from '-838:59:59' to '838:59:59'
YEAR() A year in two-digit or four-digit format.
Note: Values allowed in four-digit format: 1901 to 2155. Values allowed in two-
digit format: 70 to 69, representing years from 1970 to 2069

*Even if DATETIME and TIMESTAMP return the same format, they work very differently. In an
INSERT or UPDATE query, the TIMESTAMP automatically set itself to the current date and time.
TIMESTAMP also accepts various formats, like YYYYMMDDHHMISS, YYMMDDHHMISS,
YYYYMMDD, or YYMMDD.
Constraints on Columns:
After the data type, you can specify other optional attributes for each column:
NOT NULL : Each row must contain a value for that column, null values are not allowed
DEFAULT value: Set a default value that is added when no other value is passed Page | 77

UNSIGNED : Used for number types, limits the stored data to positive numbers and zero
AUTO INCREMENT : MySQL automatically increases the value of the field by 1 each
time a new record is added
PRIMARY KEY : Used to uniquely identify the rows in a table. The column with primary
key setting is often an ID number, and is often used with AUTO_INCREMENT.
PHP Connect to MySQL:
PHP work with a MySQL database using either:
 MySQLi extension (the "i" stands for improved)
 PDO (PHP Data Objects)
PDO will work on 12 different database systems, whereas MySQLi will only work with
MySQL databases.
when using MySQLi extension there are two ways to conncect with MySQL database.
1. MySQLi (object-oriented)
2. MySQLi (procedural)
Before we can access data in the MySQL database, we need to be able to connect to the server:

1. Open a Connection to MySQL using MySQLi Object-Oriented:


<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname="databasename";
// Create connection
$conn = new mysqli($servername, $username, $password,$dbname);
// Check connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
2. Open a Connection to MySQL using MySQLi Procedural:

<?php
$servername = "localhost";
Page | 78
$username = "username";
$password = "password";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>
PHP Create a MySQL Database Using MySQLi object oriented.
A database consists of one or more tables.nThe CREATE DATABASE statement is used to
create a database in MySQL.
Ex: create a database named "myDB":
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
// Create database
$sql = "CREATE DATABASE myDB";
$res= conn->query($sql);
if ($res)
{
echo "Database created successfully";
}
else
{
echo "Error creating database: " . $conn->error;
} Page | 79

$conn->close();
?>
PHP Create a MySQL Table Using MySQLi object oriented:

A database table has its own unique name and consists of columns and rows. The CREATE
TABLE statement is used to create a table in MySQL.

Ex: create a table named "Students", with five columns: "id", "firstname", "lastname",
"email" and "contactno":

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
// sql to create table
$sql = "CREATE TABLE students (id INT(6),firstname VARCHAR(30),
lastname VARCHAR(30),email VARCHAR(50),contactno int(10))";
$res=$conn->query($sql);
if ($res)
{
echo "Table Student is created successfully";
}
else
{
echo "Error creating table: " . $conn->error;
}
$conn->close();
?>
Insert Data Into MySQL Using MySQLi object oriented: Page | 80

After a database and a table have been created, we can start adding data in them.
Here are some syntax rules to follow:
 The SQL query must be quoted in PHP
 String values inside the SQL query must be quoted
 Numeric values must not be quoted
 The word NULL must not be quoted
Syntax:
INSERT INTO table_name (column1, column2,...) VALUES (value1, value2,...);
insert.php:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn-
>connect_error); }
$sql = "INSERT INTO MyGuests (firstname, lastname, email,contactno)VALUES
('giri', 'babu', '[email protected]',1234567890)";
$res=$conn->query($sql);
if ($res)
{
echo "New record created successfully";
}
else
{
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>

Select Data From a MySQL Database Using MySQLi object oriented: Page | 81

The SELECT statement is used to select data from one or more tables. There are two ways to
select data from a table.
1. Selecting Selected columns from a table.
Syntax: SELECT column_name(s) FROM table_name.
Ex: Select firstname,lastname from students.
2. we can use the * character to select ALL columns from a table:
Syntax: SELECT * FROM table_name.
Ex: Select * from students;
Select.php:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, firstname, lastname FROM students";
$result = $conn->query($sql);
if ($result->num_rows > 0)
{
// output data of each row
while($row = $result->fetch_assoc())
{
echo "id: " . $row["firstname"]. " - Name: " . $row["lastname"]." ". $row["email"]."<br>";
}
}
else
{
echo "0
results"; }
$conn->close(); Page | 82

?>

In the above program, First, we set up an SQL query that selects the firstname,lastname and
email columns from "students" table. The next line of code runs the query and puts the resulting data
into a variable called "$result".
Then, the function num_rows() checks if there are more than zero rows returned. If there are
more than zero rows returned, the function fetch_assoc() puts all the results into an associative array
that we can loop through. The while() loop loops through the result set and outputs the data from the
firstname, last name and email columns.

Delete Data From a MySQL Table Using MySQLi object oriented:


The DELETE statement is used to delete records from a table:
Syntax: DELETE FROM table_name WHERE some_column = some_value;
Ex: Delete from students where contactno=12345;

Note: The WHERE clause specifies which record or records that should be deleted. If you omit the
WHERE clause, all records will be deleted!

Delete.php:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
// sql to delete a record
$sql = "DELETE FROM students WHERE contactno=12345";
$res=$conn->query($sql);
if ($res)
{ Page | 83

echo "Record deleted successfully";


}
else
{
echo "Error deleting record: " . $conn->error;
}
$conn->close();
?>
Update Data In a MySQL Table Using MySQLi object oriented:
The UPDATE statement is used to update existing records in a table:
Syntax: UPDATE table_name SET column1=value, column2=value2,...
WHERE some_column=some_value
Ex: UPDATE students SET firstname="ravi" WHERE firstname=12345;
WHERE clause specifies which record or records that should be updated. If you omit the
WHERE clause, all records will be updated!
Update.php:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn-
>connect_error); }
$sql = "UPDATE students SET firstname="ravi" WHERE firstname=12345";
$res=$conn->query($sql);
if($res)
{
echo "Record updated successfully";
}
else
{ Page | 84

echo "Error updating record: " . $conn->error;


}
$conn->close();
?>
Limit Data Selections From a MySQL Database:
Select statement of MySQL is used to return all the records. Returning a large number of
records can impact on performance. MySQL provides a LIMIT clause that is used to specify the
number of records to return.
Assume a table contains 100 members students records but we wish to select all records from 1
- 30 (inclusive) from a table. The SQL query would then look like this:
$sql = "SELECT * FROM Orders LIMIT 30";
If we want to select records 16 - 25 (inclusive) Mysql also provides a way to handle this: by
using OFFSET.
The SQL query return only 10 records, start on record 16 (OFFSET 15)":
$sql = "SELECT * FROM Orders LIMIT 10 OFFSET 15";
Also the above command written in below format also valid
$sql = "SELECT * FROM Orders LIMIT 15, 10";
Note: The numbers are reversed when you use a comma.

Query string in PHP:


Imagine you have a URL:
http://www.mywebsite.com/page.php?id=5&name=php
Then the query string is: ?
id=5&name=php
In this case, the query consists of two parts: a key id with value 5, and a key name with
value php.
You can access the value of the query string keys using this code:
$id = $_GET['id'];
The above code gets the value of id, which is 5 in this case.
File Handling
What is a file?
A file is a collection of data that is stored on disk and that can be manipulated as a single unit
by its name. Page | 85

What is a directory?
A directory is a file that acts as a folder for other files. A directory can also contain other
directories (subdirectories); a directory that contains another directory is called the parent directory of
the directory it contains.
A directory tree includes a directory and all of its files, including the contents of all
subdirectories. (Each directory is a "branch" in the "tree.") A slash character alone (`/') is the name of
the root directory at the base of the directory tree hierarchy; it is the trunk from which all other files or
directories branch.

Handling files: File handling is the concept of reading the file contents as well as writing the
contents. PHP providing no of functions to read and write the file contents. If we want to read and
write contents of file, first we need to open the file with the specified file mode.
Mode specifies the access type of the file or stream. It can have the following possible values:

“r”(Read) : It represents Read only. It reads the file contents. It starts at the
beginning of the file.

“r+”(Read/Write) : It represents Read/Write. It starts at the beginning of the file.

“w”(Write) : It represents Write only. It opens and clears the contents of file or
create a new file if it doesn‟t exist.

“w+”(Write/Read) : It is same as Write mode, we can also read the file contents. It
opens and clears the contents of file or creates a new file if it
doesn‟t exist.

“a”(append) : It represents Write only. It opens and writes the new text at end
of the file or creates a new file if it doesn‟t exist.

“a+”(append/Read) : It is same as append mode, we can also represents Read/Write. It


preserves the file‟s content by writing to the end of the file.

File handling Functions:

1. fopen( ) (Function open file or URL):


The fopen() function in PHP is an inbuilt function which is used to open a file or an URL. It
contains two arguments filename and filemode. The filename and mode to be checked are sent as
parameters to the fopen() function and it returns a file pointer resource if a match is found and a False on
failure. The error output can be hidden by adding an „@‟ in front of the function name.
Syntax: fopen ( $file, $mode) Page | 86

Here $file: It is a mandatory parameter which specifies the file.


$mode: It is a mandatory parameter specifies the access type of the file or stream

Open file for write mode:

Ex: $my_file = 'file.txt';

$handle = fopen($my_file, 'w') or die('Cannot open file: '.$my_file); //implicitly creates file

Read a File: fread() is a function used to read data from a file.

$my_file = 'file.txt';

$handle = fopen($my_file, 'r');

$data = fread($handle,filesize($my_file));

Write to a File: fwrite() is a method used to write new data into a file.

$my_file = 'file.txt';

$handle = fopen($my_file, 'w') or die('Cannot open file: '.$my_file);

$data = 'This is the data';

fwrite($handle, $data);

Append to a File: append is a method used to add new data at end of an existing file.

$my_file = 'file.txt';

$handle = fopen($my_file, 'a') or die('Cannot open file: '.$my_file);

$data = 'New data line 1';

fwrite($handle, $data);

$new_data = "\n".'New data line 2';

fwrite($handle, $new_data);

Close a File: fclose() is a function used to close a file.

$my_file = 'file.txt';

$handle = fopen($my_file, 'w') or die('Cannot open file: '.$my_file);


//write some data here

fclose($handle);

Delete a File: unlink() is a function used to delete an existing file.


Page | 87
$my_file = 'file.txt';

unlink($my_file);

You might also like