0% found this document useful (0 votes)
6 views91 pages

Open Source PhpLab Manual

The document is a lab manual for the Open Source Lab course (CA323) at Integral University, Lucknow, for BCA students in their 3rd year, 6th semester during the 2020-2021 session. It outlines the course objectives, outcomes, guidelines for students, and a list of lab experiments focusing on PHP, MySQL, and Linux technologies. Additionally, it includes a revision history and the department's vision and mission statements aimed at fostering quality education and professional development.

Uploaded by

WITCHER
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)
6 views91 pages

Open Source PhpLab Manual

The document is a lab manual for the Open Source Lab course (CA323) at Integral University, Lucknow, for BCA students in their 3rd year, 6th semester during the 2020-2021 session. It outlines the course objectives, outcomes, guidelines for students, and a list of lab experiments focusing on PHP, MySQL, and Linux technologies. Additionally, it includes a revision history and the department's vision and mission statements aimed at fostering quality education and professional development.

Uploaded by

WITCHER
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/ 91

INTEGRAL UNIVERSITY LUCKNOW

Dasauli, Bas-ha Kursi Road, Lucknow – 226026


Department of Computer Application

LAB MANUAL

Session : 2020-2021

Subject Name : Open Source Lab

Subject Code : CA323

Branch : BCA

Year : 3rd

Semester : 6th

Department Of Computer Application


(CA323)
Revision History
REVISION HISTORY
REVISIO AUTHOR(S) REVIEWER(S DATE OF OWNE SUMMARY OF
N ) RELEASE R CHANGES
Revision -1 Ayaz Ahmad Internal 04/03/202 HOD - Initial Release
Reviewers 2 CA
Revision -2 Mr. Arshad Ali Departmental 05/03/202 HOD - Major revisions made.
QAC 2 CA Incorporated review
comments from
departmental QAC into
Revision-2

Department Of Computer Application


(CA323)
Vision

 To lead the teeming millions of the world through the wilderness of ignorance and illiteracy, as
"Kindly Light" (Exodus 13:21) with the resounding divine proclamation. "Read: Thy Lord is the
most bounteous (Quran 30:96:3)." and to educate them in the most constructive and innovative
ways.

 To integrate the ebullience, intellect and dynamism of youth with decency, decorum, discipline
and dedication through value-based quality education.

Mission

 To make every student a role model of intellectuals and torch bearer for others all over the world
through his / her inspiring existence.

 To inculcate a spirit of confidence, self-respect and firm commitment in students along with
farsighted wisdom and understanding.

 To make India a self-reliant and dominant G-1 country recognized for quality education,
higher economic growth and valuable moral practices.

Department Of Computer Application


(CA323)
Programme Educational Objectives (PEO)

 To acquaint students about principles of system analysis, design, development and project management.
 To impact knowledge about various sub domains related to the field of computer science and
applications.
 To apply IT practices to model and analyze the real-life problems and interpret the results.
 To build and lead cross-functional teams, upholding the professional responsibilities & ethical values.

Programme Outcomes (PO)

 Ability to demonstrate knowledge of Computer science and its applications in order to enhance basic
understanding of various software technologies.

 Ability to analyze and identify various business and technical problems to further solve problems with
effective communication.

 Ability to adapt analytical, logical and managerial skills with the technical aspects in order to design and
deployreliable software programs andapplication for real
world problems.

 Ability to investigate complex problems and provide computer-based solutions.

 Ability to understand and deliver ethical, social and cultural responsibilities in professional environment
as an individual and team.

 Ability to adapt new technologies for upgrading their skills and contributing to a lifelong learning.

 Ability to create and manage multidisciplinary projects and successfully apply software and project
management principles.

 Ability to become employable in a variety of IT companies and government sector and also seek
entrepreneurship opportunities for the betterment of an individual and society at large.

Course outcome
Department Of Computer Application
(CA323)
 Explore different open source technology like Linux, PHP & MySQL with different packages.

 Execute Linux commands for programming.

 Execute programs of PHP with MySQL connection

 Understand, analyze and apply the role of languages like HTML, DHTML, CSS, JavaScript and PHP.

 Analyze a web page and identify its elements and attributes.

 Create web pages using HTML, DHTML and Cascading Style Sheets.

 Create dynamic web pages using JavaScript, XML.

 Build web applications using PHP.

Guidelines for the Students


Department Of Computer Application
(CA323)
1. The students should implement the given Program individually.
2. While conducting the experiments students should see that their programs would Meet the following
criteria:

I. Programs should be interactive with appropriate prompt messages, error messages if any, and
descriptive messages for outputs.
II. Programs should perform input validation (Data type, range error, etc.) and give appropriate
error messages and suggest corrective actions.
III. Comments should be used to give the statement of the problem and every function should
indicate the purpose of the function, inputs and outputs
IV. Statements within the program should be properly indented.
V. Use meaningful names for variables and functions.
VI. Make use of Constants and type definitions wherever needed.

3.Once the experiment(s) get executed, they should show the program and
results to the instructors and copy the same in their Lab Report.
4. Students should be regular and come prepared for the lab practice.
5. In case a student misses a class, it is his/her responsibility to complete that
missed experiment(s).
6. Students should bring the lab Report, class notes can be kept ready for
reference if required.

List of Lab Experiments


Week Experime Name of the Experiments Page No.
No nt No.
Week-1
Introduction of PHP 8
1

PHPisaLooselyTypedLanguage

Department Of Computer Application


(CA323)
PHPVariablesExample

Week-2
2 1 ECHOandPRINTstatementsinPHP 12
2 String FunctionsinPHP
Week-3
3 Arithmetic Operators, IncrementandDecrementOperators, 18
3 AssignmentOperatorsinPHP, String OperatorsinPHP.
4 TheifStatementinPHP, Theif…elseStatementinPHP, Theif…elseif…
elseStatementinPHP, SwitchStatementinPHP.
Week-4
5 For loopinPHP, WhileLoopinPHP, DoWhileloopinPHP 23
4
6 PHP Functions,PHP Global Variables,Array in PHP.

Week-5
5 7 The $_POST Function,The $_GET Function. 29

Week-6
6 8 Concept of Cookies. 34

Week-7

7 9 Concept of Sessions. 36

Week-8

8 10 Mysql database and connectivity. 41

Week-9

9 11 Web application. 42

WhatisPHP?

 PHPstandsforPHP:HypertextPreprocessor
 PHPisaserver-sidescriptinglanguage
 PHPscripts areexecutedon theserver
Department Of Computer Application
(CA323)
 PHP supports many databases (MySQL, Informix, Oracle, Sybase,
Solid,PostgreSQL,GenericODBC, etc.)
 PHPisanopensourcesoftware
 PHPisfreetodownloadanduse

BasicPHPSyntax

 APHPscriptstartswith<?phpandendswith?>
 ThedefaultfileextensionforPHPfilesis".php"
 APHPfilenormallycontainsHTMLtags,andsomePHPscriptingcode
 PHPstatementsareterminatedbysemicolon(;)
 In PHP, all user-defined functions, classes, and keywords (e.g. if,
else,while,echo,etc.)arenotcase-sensitive

HelloWorldexample

<html>
<body>
<?php
// Use echo to print on console
echo ‚Hello World!‛;
?>
</body>
</html>

Go to htdocs folder which is present in the apache2triad installed folder.


Therecreateafolderandsavethisprogramwith.phpextensionsuchasHello.php.

Department Of Computer Application


(CA323)
C:\apache2triad\htdocs\MyPHPProgram

To execute hello world program, type in the address bar as


follows:http://localhost/MyPHPProgram/hello.php

http://localhost/MyPHPProgram/hello.php

Department Of Computer Application


(CA323)
ErrorManagement

1. Compile-timeerrors:
 Compile-time errors are detected by the parser while it is compiling ascript.
 Thecompile-timeerrorscannotbetrappedfromwithinthescriptitself
2. Fatalerrors:
 Fatalerrorsaretheerrorsthathalttheexecutionofascript.
 Thefatalerrorscannotbetrapped.
3. Recoverableerrors:
 Recoverable errors that represent significant failures, but can still
behandledina safeway.
4. Warnings:
 Warningsarerecoverableerrorsthatindicatearun-timefault.
 Warningsdonothalttheexecutionofthescript.
5. Notices:
 Notices indicate that an error condition occurred, but is not necessarilysignificant.
 Noticesdonothalttheexecutionofthescript.

Department Of Computer Application


(CA323)
Findingerrorspresentintheprogram

<html>
<body>
<?php
echo ‚Hello World!‛;
// here ? is missing
>
</body>
</html>

Tofindtheerrorspresentintheprogramgoto:

Start->Allprograms ->Apache2triad->Apache2TriadCP

Apache2TriadCP

Department Of Computer Application


(CA323)
Thenclickon“PHPErrorlog”

PHPError log

Department Of Computer Application


(CA323)
The list of errors in the program is displayed along with the line number
wherethe error hasoccurred.

[05-Jan-2007 05:21:11] PHP Parse error: syntax error, unexpected


T_STRING,expecting','or';'inC:\apache2triad\htdocs\MyPHPProgram\
hello.phponline4

Department Of Computer Application


(CA323)
CommentsinPHP

 //Singlelinecomment(C++and Java-stylecomment)
 #Singlelinecomment(Shell-stylecomments)
 /* Multiple line
comment(C-
stylecomments)*/

PHPisaLooselyTypedLanguage

 InPHP,avariabledoesnotneedtobedeclaredbeforeaddingavaluetoit
 PHP automatically converts the variable to the correct data
type,dependingonitsvalue
 InPHP,thevariableisdeclaredautomaticallywhenyouuseit
 PHPvariablesmustbeginwitha“$” sign
 Variablesareusedfor storingvalues,liketextstrings,numbersorarrays
 ThecorrectwayofdeclaringavariableinPHP:

$var_name=value;

PHPVariablesExample
<html>
<body>
<?php
$a = 25; // Numerical variable
$b = ‚Hello‛;// String variable
$c = 5.7; // Float variableecho
‚Number is : ‛.$a.‚<br/>‛;echo ‚String is : ‛.
$b.‚<br/>‛;echo ‚Float value : ‛.$c;
?>
</body>
<html>

OUTPUT of the above given Example is as

follows:Number is:25

String is :

HelloFloatvalue:

5.7

Department Of Computer Application


(CA323)
Global and locally-scoped variables

 Globalvariablescanbeusedanywhere
 Localvariablesrestrictedtoafunctionorclass

ExampleforGlobalandlocally-scopedvariables

<html>
<body>
<?php
$x=24; // global scope

// Function
definitionfunctionmyFu
nction(){
$y=59;// local scope
echo"Variablexis:
$x<br>";echo "Variable y
is: $y";
}

myFunction();// Function call

echo "Variable x is:


$x";echo "<br>";
echo "Variable y is: $y";
?>
</body>
</html>

OUTPUT of the above given Example is as

follows:Variablexis:

Variableyis:59

Test variables outside the

function:Variablexis:24
Variableyis:

Department Of Computer Application


(CA323)
StaticKeywordinPHP

 Statickeywordisused when you first declare thevariable


 Each time the function is called, that variable will still have the
informationitcontainedfromthe lasttime thefunctionwascalled

StaticKeywordExample

<html>
<body>
<?php
// Function
definitionfunction
myFunction() {
static$x=45
;echo$x;ech
o"<br/>";
$x++;
}
// Function call
myFunction(
);myFunctio
n();myFunct
ion();myFun
ction();myF
unction();
?>
<body>
<html>

OUTPUToftheabovegivenExampleisasfollows:

45
46
47
48
49

Department Of Computer Application


(CA323)
ECHOandPRINTstatementsinPHP

 ECHO-Itcanoutputoneormorestrings
 PRINT–Itcanonlyoutputonestring,andreturnsalways1
 ECHOisfastercomparedtoPRINTasechodoesnotreturnanyvalue
 ECHOisnotafunctionand,assuch,itdoes nothaveareturnvalue
 Ifyouneedtooutputdatathroughafunction,youcanusePRINT()instead:

Example:

echo50;
print(50);
PRINTStatementExampleinPHP

<html>
<body>
<?
php // Use ‘print’ to print on console
print "Hello world!<br>***********";

?>
</body>
</html>

OUTPUToftheabovegivenExampleisasfollows:

Helloworld!
***********

Department Of Computer Application


(CA323)
String Functions in PHP

 strlen()function
 strpos()function

1. strlen()function

 Thestrlen()functionreturnsthelengthofastring,incharacters

<html>
<body>
<?
php // Displays the length of the
stringecho strlen("Hello
world!");
?>
</body>
</html>

OUTPUToftheabovegivenExampleisasfollows:

12

2. strpos()function

 The strpos() function is used to search for a specified character or


textwithinastring

<html>
<body>
<?php
/* Displays the position of ‘world’ in
thetext ‘Hello world*/
echo strpos("Hello world!","world");
?>
</body>
</html>

OUTPUT of the above given Example is as

follows:6

Department Of Computer Application


(CA323)
ConstantinPHP

 define()functionisusedtosetaconstant
 Ittakesthreeparameterstheyare:
1. Nameoftheconstant
2. Valueoftheconstant
3. Third parameter is optional. It specifies whether the constant
nameshouldbe case-insensitive.Default isfalse

ConstantstringExample

<html>
<body
> <?php
/* Here constant name is ‘Hai’ and
‘HelloFriend’ is its constant value
and trueindicates the constant value
is case-insensitive */
define("Hai","Hello
Friend",true);echo hai;
?>
</body>
</html>

OUTPUT of the above given Example is as

follows:HelloFriend

PHPExampletocalculatetheareaofthecircle

<html>
<body
> <?php
// defining constant value PI =
3.14define("PI","3.14");
$radius=15;
$area=PI*$radius*$radi
us;echo "Area=".$area;
?>
</body>
</html>

OUTPUT of the above given Example is as

follows:Area=706.5

Department Of Computer Application


(CA323)
Arithmetic Operators

 Arithmeticoperatorsallowperformingbasicmathematicaloperations

Operator Description Example Result

+ Addition $a= 2+5; $a=7

- Subtraction $a=10-2; $a=8

* Multiplication $a= 2*5; $a=10

/ Division $a=15 /5; $a=3

% Modulus $a=23 %7; $a=3.28

$a=5; $a=6
++ Increment
$a++;

$a=5; $a=4
-- Decrement
$a--;

Department Of Computer Application


(CA323)
ArithmeticOperatorsExample

<html>
<body>
<?
php // Add 20, 10 and sum is stored in $i
$i=(20 + 10);
// Subtract $i, 5 and difference is stored in $j
$j=($i- 5);
// Multiply $j, 4 andresult is stored in $k
$k=($j * 4);
// Divide $k, 2 and result is stored in $l
$l=($k / 2);
// Devide $l, 5 and remainder is stored in $m
$m=($l % 5);
echo "i = ".$i."<br/>";
echo "j = ".$j."<br/>";
echo "k = ".$k."<br/>";
echo "l =".$l."<br/>";
echo "m = ".$m."<br/>";

?>
</body>
</html>

OUTPUToftheabovegivenExampleisasfollows:

i=30
j =25
k=100
l=50
m=0

Department Of Computer Application


(CA323)
IncrementandDecrementOperators

Operator Name Description

++$a Pre-increment Increments$abyone, thenreturns$a

$a++ Post-increment Returns$a,thenincrements$abyone

--$a Pre-decrement Decrements$abyone,thenreturns$a

$a-- Post-decrement Returns$a,thendecrements$abyone

IncrementandDecrementOperatorsExample

<html>
<body>
<?
php $i=10;
$j=20;
$i++;
$j++;
echo
$i."<br/>";ech
o$j."<br/>";
// Post increment
$k=$i++;
// Pre increment
$l=++$j;
echo
$k."<br/>";ech
?> o $l;
</body>
</html>

OUTPUToftheabovegivenExampleisasfollows:

11
21
11
22

Department Of Computer Application


(CA323)
AssignmentOperatorsinPHP

 Assignmentoperator isusedtowriteavaluetoa variable

Operator Example Isthesameas

= x=y x=y

+= x+=y x=x+y

-= x-=y x=x-y

*= x*=y x=x*y

/= x/=y x=x/y

.= x.=y x=x.y

%= x%=y x=x%y

AssignmentOperatorsExample

<html>
<body>
<?php
$a=5;
echo "a=".
$a;echo"<br
/>";

$b=10;
$b += 20;
echo "b=".
$b;echo"<br
/>";
$c=15;
$c -= 5;
echo "c=".
$c;echo"<br
/>";

$d=20;
$d
*=2;echo"d=
".

Department Of Computer Application


(CA323)
AssignmentOperatorsinPHP
$d;echo"<br
/>";

Department Of Computer Application


(CA323)
$e=25;
$e /= 5;

echo "e=".
$e;echo"<br
/>";

$f=30;
$f
%=4;echo"f=
".$f;
?>
</body>
</html>

OUTPUToftheabovegivenExampleisasfollows:

a=5b
=30c
=10d
=40
e=5
f=2

Department Of Computer Application


(CA323)
StringOperatorsinPHP

Operator Name Example Result

$a="Hello"
. Concatenation $b="Helloworld!"
$b=$a ."world!"

ConcatenationAs $a="Hello"
.= $a="Helloworld!"
signment $a.="world!"

StringOperatorsExample

<html>
<body>
<?
php $a = "Hello";
$b = $a . "
Friend!";echo $b;
echo "<br/>";

$c="Good";
$c .= "
Day!";echo
$c;
</ ?>
body>
</html>

OUTPUTofthe abovegivenExampleisasfollows:

HelloFriend!
GoodDay!

Department Of Computer Application


(CA323)
TheifStatementinPHP

 Ifstatementexecutessomecodeonlyifaspecifiedconditionistrue

Syntax:

if(condition){
codetobeexecutedifconditionistrue;
}

TheifStatementExample
<html>
<body>
<?php
$i=0;

/* If condition is true,
statement isexecuted*/

if($i==0)
echo "i is 0";
?>
<body>
</html>

OUTPUT of the above given Example is as

follows:iis0

Department Of Computer Application


(CA323)
Theif…elseStatementinPHP

 If…elsestatementexecutessomecodeifaconditionistrueandsome
anothercodeiftheconditionisfalse

Syntax:

if(condition){
codetobeexecutedifconditionistrue;
}

else{
codetobeexecutedifconditionisfalse;
}

Theif…elseStatementExample

<html>
<body>
<?
php $i=1;

/* If condition is true, statement1


isexecuted,elsestatement2isexecuted*/

if($i==0)
echo "i is 0";//statement1
els
e echo "i is not 0";//statement2
?
>
<body>
</html>

OUTPUT of the above given Example is as

follows:iisnot 0

Department Of Computer Application


(CA323)
Theif…elseif…elseStatementinPHP

 If…elseif…else statement selects one of several blocks of code to


beexecuted

Syntax:

if(condition){
codetobeexecutedifconditionistrue;
}

elseif(condition){
codetobeexecutedifconditionistrue;
}

else{
codetobeexecutedifconditionisfalse;
}

Theif…elseif…elseStatementExample(Comparingtwonumbers)

<html>
<body>
<?
php $i=22;
$j=22;
/* If condition1 is true, statement1 is
executed,if condition1 is false and
condition2 is true,statement2 is executed,
if both the conditionsare false statement3
is executed */
if($i>$j)
echo"iisgreater";//
statement1elseif($i<$j)
echo "j is greater";//statement2
els
e echo "numbers areequal";//Statement3
?>
<body
>
</html>

OUTPUT of the above given Example is as

follows:numbersare equal

Department Of Computer Application


(CA323)
SwitchStatementinPHP

 Switchstatementselectsonefrommultiple blocksofcodetobeexecuted

Syntax:

switch(n){
caselabel1:
code to be executed if
n=label1;break;
caselabel2:
code to be executed if
n=label2;break;
...
default:
codetobeexecutedifnisdifferentfromalllabels;
}
SwitchStatementExample

<html>
<body>
<?
php $x=3;
/
*Expressionvalueiscomparedwitheachcaseval
ue. If it matches, statements
followingcase would be executed. Break
statement isused to terminate the
execution ofstatement.*/
switch ($x)
{
case 1:
echo"Number1";break
;
case 2:
echo"Number2";break
;
case
echo"Number3";break
;
3:defau
echo "No number between 1 and 3";

?> lt:
</body>
</html> }

Department Of Computer Application


(CA323)
OUTPUToftheabovegivenExampleisasfollows:

Number3

ForloopinPHP

 PHPforloopexecutesablockofcode,aspecifiednumberoftimes

Syntax:

for (initialization; test condition; increment/decrement)


{codetobe executed;
}

ForloopExample

<html>
<body>
<?php

echo "Numbers from 1 to 20 are: <br>";

/*in for loop, initialization usually


declaresa loop variable, condition is a
Booleanexpression such that if the
condition is true,loop body will be
executed and after eachiteration of loop
body, expression is executedwhich usually
increase or decrease loopvariable*/

for ($x=0; $x<=20; $x+


+) {echo "$x";
}
?>
</body>
</html>

OUTPUT of the above given Example is as

follows:Numbersfrom1 to20 are:

012 34 5 678 91011 121314 15 1617181920

Department Of Computer Application


(CA323)
DeclaringmultiplevariablesinforloopExample

<html>
<body>
<?php

/*Multiplevariablescanbedeclaredindeclaration
block of for loop */

for ($x=0,$y=1,$z=2;$x<=3;$x++) {
echo "x = $x,y = $y,z = $z <br>";
}
?>
</body>
</html>

OUTPUTofthe abovegivenExampleisasfollows:

x=0,y= 1,z =2
x=1,y= 1,z =2
x=2,y= 1,z =2
x=3,y= 1,z =2

Department Of Computer Application


(CA323)
WhileLoopinPHP

 While loop, loops through a block of code as long as the specified


conditionistrue

Syntax:

while(condition)
{codetobeexecuted;
}

WhileLoopExample

<html>
<body>
<?
php $i=1;

/* here <condition> is a Boolean


expression.Loop body is executed as long
as condition istrue*/

while($i<5){
echo "i is = $i <br>";
$i++;
}
?>
</body>
</html>

OUTPUToftheabovegivenExampleisasfollows:

i is =
1i is =
2i is =
3iis=4

Department Of Computer Application


(CA323)
DoWhileloopinPHP

 Do while loop will always execute the block of code once, it will then
checkthe condition,andiftheconditionistruethenit repeatstheloop

Syntax:

do{
codetobeexecuted;
}while(condition);

DoWhileloopExample

<html>
<body>
<?
php $i=1;

/* here <condition> is a Boolean expression.


Pleasenote that the condition is evaluated
after
executingtheloopbody.Soloopwillbeexecutedatleas
tonceeven if the condition isfalse*/

do
{
echo "i is = $i <br>";
$i++;
}while($i<5);
?>
</body>
</html>

OUTPUToftheabove givenExampleisasfollows:

i is =
1i is =
2i is =
3iis=4

Department Of Computer Application


(CA323)
UserDefinedFunctioninPHP

 Functionsaregroupofstatementsthatcanperformatask

Syntax:

function functionName()
{codetobeexecuted;
}

UserDefinedFunctionExample

<html>
<body>
<?php

// Function
definitionfunction
myFunction()
{
echo "Hello world";
}

// Function
callmyFunction
();
?>
</body>
</html>

OUTPUT of the above given Example is as

follows:Helloworld

Department Of Computer Application


(CA323)
SwapNumbersPHPExample

<html>
<body>
<?
php $num1=10;
$num2=20;
echo "Numbers before
swapping:<br/>";echo "Num1=".
$num1;
echo "<br/>Num2=".$num2;

// Function
callswap($num1,$
num2);

// Function
definitionfunctionsw
ap($n1,$n2)
{
$temp=$n1;
$n1=$n2;
$n2=$temp;
echo "<br/><br/>Numbers after
swapping:<br/
>";echo "Num1=".$n1;
echo "<br/>Num2=".$n2;
}
?>
</body>
</html>

OUTPUToftheabovegivenExampleisas follows:

Numbers before
swapping:Num1=10
Num2=20

Numbers after
swapping:Num1=20
Num2=10

Department Of Computer Application


(CA323)
PHPFunctions-Addingparameters

<html>
<body>
<?
php // Function
definitionfunctionwriteName
($fname)
{
echo $fname . " Refsnes.<br />";
}

echo "My name is ";


writeName("Kai Jim");//Function call

echo "My sister's name is


";writeName("Hege");//Functioncall

echo "My brother's name is


";writeName("Stale");//Functioncall

?>
</body>
</html>

OUTPUT of the above given Example is as

follows:Myname isKaiJim Refsnes.


My sister's name is Hege
Refsnes.Mybrother'snameisStaleR
efsnes.

Department Of Computer Application


(CA323)
PHPFunctions-Returnvalues
<html>
<body>
<?
php // Function
definitionfunction
add($x,$y)
{
$total=$x+
$y;return$to
tal;
} // Function call
echo "1 + 16 = " . add(1,16);
?>
</body>
</html>

OUTPUToftheabovegivenExampleisasfollows:

1+16 =17

Breakstatement
 Breakstatementisusedtoterminatetheloop
 After the break statement is executed the control goes to the
statementimmediatelyafter theloopcontainingbreakstatement

Breakstatementexample

<html>
<body>
<?php
/* when $i value becomes 3, the
loop isTerminated*/
for($i=0;$i<5;$i++)
{
if($i==3)
break;
els
e echo "$i ";
}
?>
</body>
</html>

OUTPUT of the above given Example is as


follows:01 2

Department Of Computer Application


(CA323)
Continuestatement

 There are cases in which, rather than terminating a loop, you simply
wantto skip over the remainder of iteration and immediately skip over to
thenext. Continuestatementis usedto skipa particular iterationof theloop.

Continuestatementexample
<html>
<body>
<?php
/* when $i value becomes 3, it will skip
theparticular of the loop*/

for($i=0;$i<=5;$i++)
{
if($i==3)
continue;
els
e echo "$i ";
}
?>
</body>
</html>

OUTPUToftheabovegivenExampleisasfollows:

01 24 5

PHPGlobalVariables-Superglobals

 "Superglobals"arepredefinedvariablesinPHP
 They are always accessible, regardless of scope - and can access them
fromanyfunction,classor file

ThePHPsuperglobalvariablesare:
$GLOBALS
$_SERVER
$_REQUEST
$_POST
$_GET
$_FILES
$_ENV
$_COOKIE
$_SESSION

Department Of Computer Application


(CA323)
$GLOBALS

 $GLOBALS is a PHP super global variable which is used to access


globalvariables from anywhere in the PHP script (also from within
functions ormethods)
 PHP stores all global variables in an array called $GLOBALS[index].
Theindexholdsthe name of thevariable

Example:

<html>
<body>
<?php
$a = 20;
$b = 40;
function addition()
{
$GLOBALS['c'] = $GLOBALS['a'] + $GLOBALS['b'];
}
addition()
;echo $c;
?>
</body>
</html>

OUTPUT of the above given Example is as

follows:60

Department Of Computer Application


(CA323)
$_SERVER

 $_SERVERisaPHPsuperglobalvariablewhichholdsinformationabouthead
ers,paths,andscriptlocations

Example

<html>
<body>
<?php
echo $_SERVER['PHP_SELF'];
echo "<br>";
echo $_SERVER['SERVER_NAME'];
echo "<br>";
echo $_SERVER['HTTP_HOST'];
echo "<br>";
echo $_SERVER['HTTP_USER_AGENT'];
echo "<br>";
echo $_SERVER['SCRIPT_NAME'];
?>
</body>
</html>

OUTPUToftheabovegivenExampleis asfollows:

/User/
server.phplocalh
ostlocalhost
Mozilla/4.0(compatible;MSIE8.0;WindowsNT6.1;Trident/4.0;GTB7.5;SLCC2;
.NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center
PC6.0; InfoPath.2; .NETCLR 1.1.4322)
/User/server.php

Department Of Computer Application


(CA323)
Arrayin PHP

 Anarraystoresmultiplevaluesinonesinglevariable
 InPHP,therearethreekindsofarrays:
 Numericarray
 Associativearray
 Multidimensionalarray

NumericArrayinPHP

 Numericarrayisanarraywithanumericindex

NumericArrayExample

<html>
<body>
<?
php /* An array $flower_shop is created with
threeValues- rose, daisy,orchid */
$flower_shop = array (
"rose",
"daisy"
,"orchi
d"
);
/* Values of array $flower_shop is displayed
basedon index. The starting index of an array
is Zero */echo "Flowers: ".$flower_shop[0].",
".$flower_shop[1].", ".$flower_shop[2]."";
?>
</body>
</html>

OUTPUT of the above given Example is as

follows:Flowers:rose,daisy,orchid

Department Of Computer Application


(CA323)
AssociativearrayinPHP
 AssociativearrayisanarraywhereeachIDkeyisassociatedwithavalue

AssociativearrayExample

<html>
<body>
<?
php /* Here rose, daisy and orchid indicates ID key
and5.00,4.00,2.00indicatestheirvaluesrespectively
*/
$flower_shop = array (
"rose" => "5.00",
"daisy" => "4.00",
"orchid" => "2.00"
);
// Display the array
valuesecho "rose costs
.$flower_shop['rose'].",daisy
costs".
$flower_shop['daisy'].",and
?> orchildcosts ".
</body> $flower_shop['orchild']."";
</html>

OUTPUT of the above given Example is as

follows:rosecosts5.00,daisycosts4.00,andorchildc

osts

Department Of Computer Application


(CA323)
Loopthrough anAssociativeArray

<html>
<body>
<?
php $flower_shop=array("rose"=>"5.00","d
aisy"=>"4.00","orchid"=>"2.00")
;

/* for each loop works only on arrays, and is


usedtoloopthrougheachkey/valuepairinanarray*/
foreach($flower_shop as
$x=>$x_value) {echo
"Flower=" . $x .
", Value=" .
$x_value;echo "<br>";
}
?>
</body>
</html>

OUTPUToftheabovegivenExampleisasfollows:

Flower=rose,
Value=5.00Flower=daisy,
Value=4.00Flower=orchid,
Value=2.00

Department Of Computer Application


(CA323)
MultidimensionalarrayinPHP

 Multidimensionalarrayisanarraycontainingoneormorearrays

MultidimensionalarrayExample

<html>
<body>
<?php
/* Here $flower_shop is an array, where rose, daisy and
orchidare the ID key which indicates rows and points to
array whichhave column values. */
$flower_shop = array(
"rose" => array( "5.00", "7 items", "red" ),
"daisy" => array( "4.00", "3 items", "blue" ),
"orchid"=> array( "2.00", "1 item", "white" ),
);
/*inthearray$flower_shop['rose']
[0],‘rose’indicatesrowand‘0’ indicates column */
echo "rose costs ".$flower_shop['rose'][0].
", and youget ".$flower_shop['rose'][1].".<br>";

echo "daisy costs ".$flower_shop['daisy'][0].


", and you get ".$flower_shop['daisy'][1].".<br>";

echo "orchid costs ".$flower_shop['orchid'][0].


", and you get ".$flower_shop['orchid'][1].".<br>";
?>
</body>
</html>

OUTPUT of the above given Example is as

follows:rosecosts5.00,andyou get 7 items.


daisy costs 4.00, and you get 3
items.orchidcosts2.00,andyouget1item.

Department Of Computer Application


(CA323)
PHP Forms

 Scripts will interact with their clients using one of the two HTTP
methods.Themethodsare GET and POST
 When a form is submitted using the GET method, its values are
encodeddirectlyinthe querystringportionof theURL
 When a form is submitted using the POST method, its values will not
bedisplayedthe querystringportionof the URL

The$_GETFunction

 The built-in $_GET function is used to collect values from a form sent
withmethod="get"
 Information sent from a form with the GET method is visible to
everyone(it will be displayed in the browser's URL) and has limits on the
amount ofinformationtosend(max.100 characters)
 Thismethodshouldnotbeusedwhensendingpasswordsorothersensitive
information. However, because the variables are displayed in theURL,it
ispossibletobookmark thepage
 The get method is not suitable for large variable values; the value
cannotexceed100 characters

The$_POSTFunction

 The built-in $_POST function is used to collect values from a form sent
withmethod="post"
 Information sent from a form with the POST method is invisible to
othersandhasnolimits ontheamountof informationtosend
 However, there is an 8 Mb max size for the POST method, by default
(canbechangedby settingthepost_max_sizein thephp.inifile)

Department Of Computer Application


(CA323)
The $_GET Function

ExampleForm1.html

<html>
<body>
/* form submitted using ‘get’ method, action specifies
next page which is to be loaded when button is
clicked*/
<form action="welcome.php" method="get">
// textbox is to take user
inputName: <input type="text"
name="fname" />Age: <input
type="text" name="age" />
// Submit button is to submit the value
<input type="submit" />
</form>
</body>
</html>

welcome.php

<html>
<body>
// $_GET to receive the data sent from
Form1.html
Welcome <?php echo $_GET["fname"]; ?
>.<br />Youare<?phpecho$_GET["age"];?
>yearsold!
</body>
</html>

Department Of Computer Application


(CA323)
OUTPUToftheabovegivenExampleisasfollows:

Inthisexample,when youclickonthe“submit”button,thevaluesenteredinthe
textboxareencodeddirectlyinthequerystringportionoftheURL.

Department Of Computer Application


(CA323)
The $_ POST Function

Exampleform1.html

<html>
<body>
/* form submitted using ‘post’ method, action specifies
next page which is to be loaded when button is clicked
*/
<form action="welcome1.php" method="post">
// textbox is to take user
inputName:<inputtype="text"name="fna
me"/>Age: <input type="text"
name="age" />
// Submit button is to submit the value to next
page
<input type="submit" />
</form>
</body>
</html>

welcome1.php

<html>
<body>
// $_GET to receive the data sent from
form1.html
Welcome <?php echo $_POST["fname"]; ?
>.<br />Youare<?phpecho$_POST["age"];?
>yearsold!
</body>
</html>

Department Of Computer Application


(CA323)
OUTPUToftheabovegivenExampleisasfollows:

Inthisexample,whenyouclickonthe“submit”button,thevalueswillnotbe
displayedthequerystringportionoftheURL.

Department Of Computer Application


(CA323)
Another Example for PHP

formForm.html

<html>
<head>
<title>Process the HTML form data with the
POSTmethod</title>
</head>
<body>
/* form submitted using ‘post’ method, action specifies next
page
which is to be loaded when button is clicked */
<form name="myform" action="process.php" method="POST">

//create an hidden textbox


<input type="hidden" name="check_submit" value="1" />

// textbox is to take user input


Name: <input type="text" name="Name" /><br
/>Password:<inputtype="password"name="Password
"
maxlength="10" /><br />

// Use ‘select’ tag to display the various


optionsSelectsomethingfromthelist:<selectname="Sea
sons">
<option
value="Spring"selected="selected
">Spring</option>
<option value="Summer">Summer</option>
<option value="Autumn">Autumn</option>
<optionvalue="Winter">Winter</option>
</select><br /><br />

Choose one:
//This will create radio buttons
<input type="radio" name="Country" value="USA" /> USA
<inputtype="radio"name="Country"value="Canada"/
>Canada
<inputtype="radio"name="Country"value="Other"/
>Other
<br />

Choose the colors:


//This will create checkbox
<input type="checkbox" name="Colors[]"
value="green"checked="checked" /> Green
<input type="checkbox" name="Colors[]" value="yellow"
/> Yellow

Department Of Computer Application


(CA323)
<input type="checkbox" name="Colors[]"
value="red" />Red

Department Of Computer Application


(CA323)
<inputtype="checkbox"name="Colors[]"value="gray"/
>Gray
<br />

// Submit button is to submit the value to next page


<input type="submit" />
</form>
</body>
</html>

Process.php

<html>
<body>
<?php
if (array_key_exists('check_submit', $_POST)) {
/*Converts the new line characters (\n) in the
textarea into HTML line breaks (the <br />
tag) */
$_POST['Comments'] = nl2br($_POST['Comments']);
//Check whether a $_GET['Languages'] is
setif ( isset($_POST['Colors']) ) {
$_POST['Colors'] = implode(', ', $_POST['Colors']);
//Converts an array into a single string
}

//Let's now print out the received values in the


browserecho"Your name: {$_POST['Name']}<br />";
echo "Your password: {$_POST['Password']}<br
/>";echo "Your favourite season:
{$_POST['Seasons']}
<br/><br />";
echo "You are from: {$_POST['Country']}<br
/>";echo"Colorsyouchose:
{$_POST['Colors']}<br/>";
}
else
{
echo "You can't see this page without
submitting theform.";
}
?>
</body>
</html>

Department Of Computer Application


(CA323)
OUTPUToftheabovegivenExampleisasfollows:

Department Of Computer Application


(CA323)
Date()andtime() functionin PHP
 The PHP date() function formats a timestamp to a more readable date
andtime
 A timestamp is a sequence of characters, denoting the date and/or time
atwhicha certaineventoccurred
 Somecharactersthatarecommonlyusedfordateandtime:
 d-Representsthedayofthemonth(01to31)
 m-Representsamonth(01to12)
 Y-Representsayear(infourdigits)
 l(lowercase'L') -Representsthedayoftheweek
 h-12-hourformatofanhourwithleadingzeros(01to12)
 i-Minuteswithleadingzeros(00to59)
 s-Secondswithleadingzeros(00to59)
 a-LowercaseAntemeridiemandPostmeridiem(amorpm)

Example

<html>
<body>
<?php

// display the date in the format


YYYY/MM/DDecho "Today is " .
date("Y/m/d") . "<br>";
// ‘l’ is used to display the day
echo"Todayis".date("l")."<br>";
// display the time in the format
HH:MM:SSecho "The time is " .
date("h:i:sa");

?>
</body>
</html>

OUTPUT of the above given Example is as

follows:Todayis2014/08/19
TodayisTuesday

Thetimeis09:13:22am

Department Of Computer Application


(CA323)
How to connect to MYSQL database
usingPHP
To connect MYSQL using PHP go to:

http://localhost//phpmyadminEnterthe username andpassword

Givethedatabasenameinthefield‘createnewdatabase’

Clickoncreatebutton

Department Of Computer Application


(CA323)
Create a new table in the database by giving a table name and number of
fieldsthenclick onGo

Department Of Computer Application


(CA323)
To give field name to the created table, write the field name in the ‘field’
column,select the data types for each fields, specify the length of each field then
click onsavetosave the fieldsandclick onGo

Department Of Computer Application


(CA323)
WhenclickedonGothetablefielddetailswillbedisplayed

Department Of Computer Application


(CA323)
Toinsertvaluesinthefield,gotoinsertandenter thevalues.ThenclickonGo

Toviewthecreatedtable,gotobrowse

Department Of Computer Application


(CA323)
Toinsertthevalues,gotoSQLandwritethequerytoinsertthevaluesandclick
onGo

SQLqueryforinsert:

Syntax:

Insertintotable_namevalues(‘value1’,’value2’,…);

Example:

InsertintoLoginvalues(‘Radha’,’hello’);

Department Of Computer Application


(CA323)
Toupdatethevalues,gotoSQLandwritethequerytoupdatethevaluesand
clickonGo

SQLqueryfor update:

Syntax:

Updatetable_namesetfield_name=’value’wherefield_name=’value’;

Example:

UpdateLoginsetpassword=’abcde’wherename=’Radha’;

Department Of Computer Application


(CA323)
Todeletethevalues,gotoSQLandwritethequerytodeletethevaluesandclick
ongo

SQLqueryfordelete:

Syntax:

Deletefromtable_namewherefield_name=’value’;

Example:

DeletefromLoginwherename=’Radha’;

Department Of Computer Application


(CA323)
The functions used to connect web form
totheMYSQL database:
mysql_connect():

This function opens a link to a MySQL server on the specified host (in
thiscase it's localhost) along with a username (root) and password (q1w2e3r4/).
Theresultof theconnectionisstoredinthe variable$db.

mysql_select_db():

ThistellsPHPthatanyquerieswemakeareagainstthemydbdatabase.

mysql_query():

Usingthedatabaseconnectionidentifier,itsendsalineofSQLtotheMySQL
server to be processed. The results that are returned are stored in
thevariable$result.

mysql_result():

Thisisusedtodisplaythevaluesoffieldsfromourquery.Using$result,we go to
the first row, which is numbered 0, and display the value of the specifiedfields.

mysql_result($result,0,"position")):

Thisshouldbetreatedasastringandprinted.

Department Of Computer Application


(CA323)
Display the data from MYSQL database
inweb form
<html>
<body>
<?php
// Open MYSQL server connection
$db = mysql_connect("localhost", "root","q1w2e3r4/");
// Select the database using MYSQL server
connectionmysql_select_db("mydb",$db);
/* Using the database connection identifier, it
sendsa line of SQL to the MySQL server to be
processedand the results are stored in the
variable
$result. */
$result = mysql_query("SELECT * FROM employees",$db);
// Displaying the details in a
tableecho "<table border=1>";
echo
"<tr><th>Name</th><th>Position</th></tr>";
while ($myrow = mysql_fetch_row($result))
{
printf("<tr><td>%s %s</td><td>%s</td></tr>",
$myrow[1], $myrow[2],$myrow[4]);
}
echo "</table>";
?>
</body>
</html>

Department Of Computer Application


(CA323)
OUTPUToftheabovegivenExamplewouldbe:

Department Of Computer Application


(CA323)
Insert the data into MYSQL database
usingweb form
<html>
<body>
<?php
if ($submit) {
// Open MYSQL server connection
$db = mysql_connect("localhost", "root","q1w2e3r4/");
// Select the database using MYSQL server
connectionmysql_select_db("mydb",$db);
/* Write insert query and assign the query in
$sqlVariable */
$sql = "INSERT INTO employees
(first,last,address,position)VALUES('$first','$last',
'$address','$position')";
// Execute the query
$result = mysql_query($sql);
echo "Thank you! Information entered.";
}
else
{
// display form
?>
<formmethod="post"action="<?phpecho$PHP_SELF?
>">First name:<input type="Text"
name="first"><br>Last name:<input type="Text"
name="last"><br>Address:<input type="Text"
name="address"><br>Position:<input type="Text"
name="position"><br>
<input type="Submit" name="submit"
value="Enterinformation">
</form>
<?php
} // end if
?>
</body>
</html>

Department Of Computer Application


(CA323)
OUTPUToftheabove givenExamplewouldbe:

Department Of Computer Application


(CA323)
Department Of Computer Application
(CA323)
Update the data present in
MYSQLdatabase using webform
<html>
<body>
<?php
// Open MYSQL server connection
$db = mysql_connect("localhost", "root","q1w2e3r4/");
// Select the database using MYSQL server
connectionmysql_select_db("mydb",$db);
if ($id) {
if ($submit) {
// Write UPDATE query and assign to $sql Variable
$sql = "UPDATE employees SET
first='$first',last='$last
',address='$address',
position='$positio
n'WHERE id=$id";
// Execute the query
$result = mysql_query($sql);
echo "Thank you! Information updated.";
}
else
{

// Write query to SELECT data from table


$sql = "SELECT * FROM employees WHERE id=$id";
// Execute the query
$result = mysql_query($sql);
// Fetch the values
$myrow = mysql_fetch_array($result);
?>
<form method="post" action="<?php echo $PHP_SELF?>">
<input type=hidden name="id" value="<?php echo
$myrow["id"] ?>">
First name:<input type="Text"
name="first"value="<?phpecho$myrow["first"]?
>"><br>
Last name:<input type="Text"
name="last"value="<?phpecho$myrow["last"]?
>"><br>
Address:<input type="Text"
name="address"value="<?
phpecho$myrow["address"]?>"><br>
Position:<input type="Text"
name="position"value="<?
phpecho$myrow["position"]?>"><br>
<input type="Submit" name="submit"

Department Of Computer Application


(CA323)
value="Enterinformation">
</form>

Department Of Computer Application


(CA323)
<?php
}
}
else
{
// display list of employees
$result = mysql_query("SELECT * FROM
employees",$db);
while ($myrow =
mysql_fetch_array($result))
{printf("<ahref=\"%s?id=%s\">%s%s</a><br
>",
$PHP_SELF, $myrow["id"],$myrow["first"],
$myrow["last"]);
}
}
?>
</body>
</html>

Department Of Computer Application


(CA323)
OUTPUToftheabovegivenExamplewouldbe:

Department Of Computer Application


(CA323)
Department Of Computer Application
(CA323)
Delete the data from MYSQL
databaseusing webform
<html>
<body>
<?php
// Open MYSQL server connection
$db = mysql_connect("localhost", "root","q1w2e3r4/");
// Select the database using MYSQL server
connectionmysql_select_db("mydb",$db);
if ($id) {
if ($submit) {
// Write DELETE query to delete data from table based on ID
$sql = "DELETE FROM employees WHERE id=$id";
// Execute the query
$result = mysql_query($sql);
echo "Thank you! Information deleted.";
}
else
{
// Write SELECT query to select data from table based on ID
$sql = "SELECT * FROM employees WHERE id=$id";
$result = mysql_query($sql);
$myrow = mysql_fetch_array($result);
?>
<form method="post" action="<?php echo $PHP_SELF?>">
<inputtype=hiddenname="id"value="<?
phpecho$myrow["id"]?>">
First name:<input type="Text"
name="first"readonly="readonly"
value="<?php echo $myrow["first"] ?
>"><br>Last name:<input type="Text"
name="last"
readonly="readonly"
value="<?php echo $myrow["last"] ?
>"><br>Address:<input type="Text"
name="address"
readonly="readonly"
value="<?php echo $myrow["address"]?
>"><br>Position:<input type="Text"
name="position"
value="<?php echo $myrow["position"]?>"><br>
<input type="Submit"
name="submit"value="Delete
information">
</form>
<?php
}

Department Of Computer Application


(CA323)
}
else

Department Of Computer Application


(CA323)
{
// display list of employees
$result = mysql_query("SELECT *
FROMemployees",$db);
while ($myrow =
mysql_fetch_array($result))
{printf("<ahref=\"%s?id=%s\">%s%s</a><br
>",
$PHP_SELF, $myrow["id"],$myrow["first"],
$myrow["last"]);
}
}
?>
</body>
</html>

OUTPUToftheabovegivenExamplewouldbe:

Department Of Computer Application


(CA323)
Department Of Computer Application
(CA323)
Department Of Computer Application
(CA323)
Hostingyour domainusing cPanel
Step1:

RegisteryourrequiredDomainnamebyvisitinggodaddy.com

Department Of Computer Application


(CA323)
Step2:

BuyrequireddomainSpacetouploadyour code

Department Of Computer Application


(CA323)
Step3:

LaunchyourcPanel–your-domain-name.com/cPanel

ProvideyourcPanelusernameandpasswordclickonlogin

Department Of Computer Application


(CA323)
Step4:

ClickonfileManger

Department Of Computer Application


(CA323)
Step5:

ClickonWebrootand Go

Department Of Computer Application


(CA323)
Step6:

SelectthePublicFolder_html

Department Of Computer Application


(CA323)
Step7:

ClickonUpload

Department Of Computer Application


(CA323)
Step8:

Clickonthechoosefiletouploadyourcode

Note:

Oncethecodeisuploadedyourwebsitewillbelive oninternet.Thatyou
cancheckwithopenthebrowserwithyour-domain-name.com

Department Of Computer Application


(CA323)
Step9:

Tocreatedatabase –clickonthephpMyAdmin

Department Of Computer Application


(CA323)
Step10:

ManageyourTablesanddatabaseonphpMyAdminconsole

Department Of Computer Application


(CA323)
Step11:

ImportingDatabaseortablebyclickingonimport

Department Of Computer Application


(CA323)
Step12:

Exportingyourdatabasetolocalmachine

Department Of Computer Application


(CA323)

You might also like