Cca61 Oss

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 140

oper Soue Softcode'- is coce that ts desired bo ke

moolify ard
Putlicly acesile ’angone (an Aee,

d'Atóbute thu cce as they dee ft ynt


deb
Eq!- n , Fiaefox , VLC mecla payel, pache Heb feive

Advantaqes af oss:
>Fledtsüty and oqtt
2> Speed
3 cOst- Efe ctivereks
V4 4S AbiUty to stelt Srmcl
S All PAcqkams ale fee b use
oSS teh-PHP IYSSL)Apache and css/Tavoserfpt poti2
leoks atke web Pago
handles dl the Manaq es ael
tu data,
web Selve

HTML >Hyfel Tesd bukup Larquaqe afplcotens


’ UAed to cAeat web Rges § web te web
2wtolely
24 used Lanquce on
con clecb a stttc vebait by HTL Only
> We qabe conten
eq <htm)
<headyitle >. . ItYtHle>ZIheodyhodyslhtmy
<bocy h s p . ips<this
ITke Kespnda which defnes tHett how uebbavse
HTNL Toqs'-cue cornent .
win faral _ Usplay thi
s\Mn pltopenhg toq clotrg teg, Content
TE ontain
unelogec togs.
But Sone HTML toqs oe e ett to cih
Bhewde reools t fom bop to bottom and
togap tfoot, (oY )
tetfeot,
l, tol theod,
ked, ,tbady, th totr, tatle,
Togs' Tabie HTML
tel
defiritor
list <dl)
ungldeds <uls
okjects bdoops< Kirags<aea
cbjTo
et Troge HTML
bsey°p ard archoras Toqs: Link HTML
<dely l4SYtcdes loddres'y (brs <Sarnps
atbrs (strorg
lsie
h6
<huhs <hgs.chas <hib, PTags Text HTML
skyle trk,mela§ title, DocTYPE,
Tags eta HTML
Rule yontel Hoi <h
tne bleak <br Toqs'- Cincloded
Eq
yt Jk</tag content KBag
Syrtu:
tasks oileent fellm H7ML atog Evely
ackes thele vofin
c enclesed must toga HTM l
HTHL Folmn Toqs'- folm, npuk, testaaa, beledt, eptBr, bakter

Duna'e
9 web contenti bHeb,ath content that tonstntty ou
egulacly change, kasod on use nteactions, tmng g otheu
Plasneees that dekiine what content s detv eed to tu
s e tet, audio, videe, tormab,outuhe, fhTeitle, gpoe
Eq <head
<seript Src"htps: |)ajox. gege apis -(cnlajox|lHbs/jqueuy/

Anhepd,todJAs
chocty style"text -Lgni tentu' td bedy'"
,9pochiEnteu you colas choite cikis
<button bype ="button' onclk"chargecelotoS 3
Colod
</buttons

furcton chargeiolett)sabak gbsdk


vl colon "#+(rmath. adon. () * I6712/5/o). toShin C);
gC'body"). ss ("backgreund colon", coled); n
</sept>
<tbody's
HTML5- TH in the fth and ceernt velsion bf .
Tt has irrpioved the maikup avoilae a downen; od
has fntio ppicaton pogranorig inteoces (API) ad
Doteunent ohjeet rnodel lDon)

dicuwing _ anmaten Nigcarvs, OUtine stage. mralat


elak,
eq: ebeded tot
cucio ad video , clag dcP,gerlocotren, donts
web APls etc...

anves! It TA use to dau qrophies vA nq Seiptng Largage


Tavleript 7he Lcon vass Clernernt A eoly ot Contanee foe
J'Ke Jarquate to dicus t grefly
crcphics, you muat naela seviptng mist
byuaing tee doarnasL Loq, to whieh you
corvas b y w e U
leate a cavas bhck ceuvas
an P so that Javascpt wl krow
also asn reat 'oe than canva Poge.
Poge.
PE iA agCessirg . nle can
Eqi- Chtmlshead<title} Cxnvas KIEHS olo
booy' id 'my lanvas
Koanvas width - '20
v herght "oo skyle.
Jboldel! 1Px sld #dsdd leánvss
Ksiptre tet ownripl"y
ck=docurrert qet Elernent ByT C ore Coniotr:a);
myaras" J. oeé
vas ttcgetlortet ' d J ; d )
tet
Ctx beginatbe);
4o,
ac/9s,5O, O, 2 * Moth. PI))
ctx dtekeyelow';

</ scipt
cleat etele or polty of cob
ciaoe
aYc)->Method wed o
Mettod to aetuell dawte ale oD thu courva
<boke) ’
ce-;rewioht
el'ssto e e: He;
rM15Audio Toq is Ukedl to define Sourds Seh as vst
ucio clps. Thele ade s Apreuted le fenat
and othel
HTMLS cudio tag
A mp3 2 Wav 3 C1g.
Eg audio contio lss
aucio/mfg
</auoio
Attutbutes d HrLsAudio Taq' diples
itt de~ires thi oudio tonti os hek
hih t drlaed
Contioh
wtth pleylruse utons . tlaut lana
flayng
that the cudde uko
2> cuuteplay- it gpecites
thot the oudio fle widstaiblegai
D SFecites
vely bime
4 mutedit i wied to mute
the autto view to yploode
S pleloodit sreifes
when a Foge loods

MIMEE TYe-(moltipwpo e Trtemet nail Extenston)o)


rps
HTML5 vides taghe ME video tog is ssed r
Sthearing video Ples bs sochas a
Ch the web foge %Suppoted t o t
1> mp4 2) webM 3> 0q9
gdleo cortiek
<ioute sr "rovie.rta'type vigleo /rp4
<u)de
Alttbute ot H7nL5 ioleo toq'
>conto it defirres. th
video otios wteh ts
i 1 i o Playlrouse futtons
2$ beight vaed to set th berght th violeo playun o
3yWotohvsed to
4> Postelt speiies the. Trioge whick is
liplay
ohen the video is not poed. ed o
5>autoblayvdeo will stat
Plang

<htmisheadstittes Ititfe lhead)


<hocys <his playng video 4hs PEs\cbun
<bedys po
<video Src" contioy
Pay
widtk"eaht ' a t
Sony,mhis v'deo (aonot
vdeos</bedys htnys
csS Lçocgstyesheet ). KARAed to cfry thu style
n the web age whteh rs mode up bf HTMi elererts
IF AOvile veious
deseribes the took f thu uebpage IE
ate Piopettes svch s kackojbund colen, podolng io
malgirn, boldelcoed cnd many mede to styleo ebpage
Fack pepelty m depelated byo G) Syrtax-jn bock p
g hocy style =teKt-atign; certey's
bue; font-sùze:95Px.font -Style:itaici s
<P Style"colo!
BoA (ternputer afiation )
(ltocy
in thu earents
HTM! 220
I> Doline css vnihg stye
attibub orty
csscss sing <Styestg
2rehc er) bedde
3y Extelral css ll css Piopelty îna seraloa.C&sfiea
then hctide thu Ale urth t#M le s
tagin ectien,
the css
Inline cSS!-Ipline css contains n
Khown as Sline css,This
attoched th elerent is uatng thu style ottiput
tag
Apefed witfhin ar t TA phit"s
Style àekgleurscoledl
Ebedy style
be usel toappy a Unique style
leent. T0 Ae Tnine styles, add tha stye
aHEiba do thanelevnt tegihi stye attribut can tontat
Totenal Shyle sheet A htelral Stye dheet may be we!
Hone singe foge has a niqoe style Tntinal stylea
defined, wthin tesyle> clonent, nside k bead
Pege:
Eq: heodscstyles
bodyeBaskqkoundoel;linan;
Colo roAoon;
maigio-et:
Y<Tstyles 4ofr;
heody
Ext
the elrnal cos- an esctelnad Style
oo
Foch oqe Oestt ente webiib by aheel
changig you can chorge
jut one file
7rcluoe a veferente
Ale inoicle. ttcinkselernenthe to theey P

oside
Eq <heod
Beod ection heinky exteiaJ' ¢
elernent qoes '
CIbed Seheet tyre"'ktleet"
<lheody
Eq't rryty le.csss
mystye. css
An enteral s s
tie hotd not 'torte witen o n
The sle rust Be contain any htd
colal iqhthses thlpety yele
ololi rovy; ralgin--ledt :20 pr 2opx
cut */. Commert
Comment ard enoly
A CSS

olor Yed
J*This is asinqle-tine cornrert */
test-aqr! Centel)

}A amuli -line (oroent */


This
maniputota tATML elemet
alow you to setect end clernett based
CSs. Selectolsi- Tt
ue Üsd to fd os select ) HTML
med ,9hdn
(SS sele cbos ttritute,^
cla, tyre,
o theu fod, elemerti based ontoeVem
Elernent sele cton' Tt seleets
is
text-aen! (ente,
ed).
ColoA'sÏn)
K/Styleslbesds
olfected by tko stule </ps)
kheciy rap win be
tt Tdseleetok ases tt ttibut ar NL
>
TDSlectofThe elernent . Ar id shod be onae
speifrc spei r c
elerent to seect a ar elerent wit o
A
Ahash Toselect
oh So a foe, fo c e elernet
choacte],tollowes b tke
-style

tet- alrqn: cente,

stylestheods
HellO

Aelectof:7he claus sejedtt selecta elerent


>class eleroent with a
atibute .D Aelect
a geittc clas fnlowed byh .
peeite class, ut apeicdchalocel,

Sq'- <Styles
" lente
tet-olrni Lelt i

YStyks<lheodylbodyylh, cass ="center'"s Heieo)


22)
mdfcla ssCentel
Helle
bet-align :(entet;
Colos:yed;
Y</styleslheadslboolyshy tlastenbes "> Aelo hs
<P coss"ente' BcA .Iry <lbeclysdhtnsaesy
) troupirg Selectol You con qhoup thu eletl to minimize
the
Lobyi2 b912 ot tgo
Colol: ed;

Srallee
<lbty
Stule Sheet Popeties. Tt % csed fos bockgrnd eet.
y Packqourd- cotot: booys bqrolot: hbocaye;
Bq-hage , boolybg- irnage iur) (";rogejrq
iS bg-nage;UCimage. pra
i>B repeat ihooly repeat- x) -ahpwirel
b-Yefeati

» Bg- atteteent, bg- posittor i right t i

(ss Text:
Text colok: The color Popeity
ften
ve
pectreo
t
byi
rpr
wsth css,a colo s rOst
> HEx Vue- like ff0opn
’RGB Vaure - (ike qb
rgb(265, ,o)
>colo rome-like yed"
q'bocly!
toloX! uej
3.

Celos :vglQsS.ODi
Toct Algbment! 7he toct-align popeety s ket h
how ontoJ agrment dq Text co be centeledn n
justr) ed,hen ta%
cLlined to toe et
Ctched s
tct evceyline
ight màlgfnsiaie Sbaight.
has ead widt% cnd lelt
toct-align! (ente;

text- aligr:righti

text-aligh:jes ityi
3Tet -Decokctron: The tert-deoAattor prcfetyS LAeo o
Set or erore detorcton fom f t . ie ext-dewstO
221
or desrn puore .
cq!<style 5D,22) y
text-aio: Cente.;
tctdeoration! uroetine;
o/P id
teoxt decorator: Gne-thuaughi This surdetln o
text-deovatien: Overine Ths s overineholb)
towetcLse hettees tn o teit.
p.uprer taef

tet- trantorrr; ouercae;

tert- transtomoi tapitaisey


sy ndert lepetty bus
text-
Text- dentatir: The ine cl a, tetxA4o
the fndentatien the fYrst odent is ike tap
seelu.

texkfndent :Fopx}

in css Aol to et the


eopesty
CSS Colok! Th
HTM! elerent ss, we ese colos ualue
Dd cr efenentTn
"O1) nt celA

toce
eolo Fomati for f D, GreEE
fosmat:RoB fom at isth shoxt
s RGB defning e colee a/7NL
BLDE ttt wsed tou iclues AR Gr. Bthat aue ange an
by speitying the he co
SImply afreste inlttnnels coleie
g55. Th: Pefely is i
oto ty clng e g60 peopety.
goitied
lalues tnthis teuat cue
2> RGBA FoArat:
contains ACeIphothat tef speafes th
that Roe4
tharutcuenuy efelenent's. The yalue of alpho is in the
Yange o.0 to Io
tanpobt aspuent

Syntax tolox rgba CR, GB, A);,


9 HEX! Hexademrnl caen bedeined aa
6-dgit colex.
tho notaton staty wth th # Symbol followed by 66chaloa
langes tom oto f. 9
Seotovc:

9Builtn ccdoxi2meos th colle ctto r ol peviasts


U,22
deAoed colols
Caols thot
thotue ded by ong a norne Such a
Jed, blue, qeen etes ib
-19haot
Syntar!

<Syles
tect- cltn'centel ;
3T.2 1

Coe:

(oo EES2EE; -nk.

thsltf
Coseeen

Hetlo rhi is RorBAfrrot Ahsson

fRele.This is Jexaseeiral faratcih,

hecyhtmdsavloo
UN:T-2
PaaONY-bcwe os.T is not Jue Umi!
ANDX Q:nur UNIX-bose
platto mto
Selvels,'s embedd ed Sytters The Keenel
Aun desktops,
seheoliuing
manage vaiwus Sotvice Soch as pocess
ricatern cheduling, basic eiphetal deuttes ,
fle and mle
Advantges
hauiney aecyeroning Knaledg e coun cwterni2 e th os
Dne con Conbi bub ,moct, libitub 5 enhounte thu teole
fr ary puupure
2y ecutyalinuk Be eurily fecttey s thr rein teasbn
táat 1t fs the most fvertHe optien
ot conpletcly ofebut TE less forcevelopels .TE S
vunelable thon ot
PE is dree touue I is disbibuted
Dnalee GNU
ALghteeqhtThe Yeqilernents tor vernnd ris
mvch less thon odher OS. ineXa
itieernoy footp
oY Slewdcun.Tt has
bre-ep- tirnes.
LpeldprOnte noX ystem provides hrh perforqcunee

oFleibiUty'I s vevy dleible.It conbe used tor desttopa


ernteddd systes S eerve

(ontro). we cour Sehect u yequired ufpolates

Linux EAertial ccrmmand:


thu command to ce Scleen, Dtis abo
$>cleal: This is rncuncls Whih can
haue to tuyp e long com
Useful when you
tonfuse the cselS
les s dilectoies.26 ceun aso
Ss: Tt shows (ist o Shou any oa chauoetos.)
(ît
Suputs wilol Catcs dietty
iles in (went
70 Ahou al iooliictaey/yie/
* oul files,i 'rmelfoth
ToSheuw.
tdsmyit /toroe rath al file ir ta ist
Display oetails od
dA -1 hidden les
gly al
+ -a Startrg wit%
Disglay al files that ave raen ny
win /NQwOFille ent90cum -r yrn $
dokereo
le Neo creab To gecit $
lello
folde lo) atile Rermove TO
Ymdy! $>
dello lello
entel Tiess Neufile mki 2)
ciectol
es moe $kdir;
al one ckeab
nes
cit copy dúr) rdir1
r todirt narne file2oy let CP
filef horne ofrle fu
ar(ocat
o to wsts /horoe/BcA/
tonDextep/ eefil-
txt cp.JAohent
dro,
Cne diáeoxy e) fle $ep!
ecoion change coPYa
cd:
ldounloods rov Neutile.tt
content f file without
UAeQ ¢o Usflay thu
4 cat:
ofertng
$ cat bca. trt
yoloruenbs
Helo bcas
bc

techo:Aed teo oispley the text.


4echo Helo fvi erdy.

ile ha e! Useo te wite


ovelwrite cany text tfrorm eutYrghla
scat
sc t baeGt
sanple tile for linux.
Hi, ThIS s a
from ttt le.
mlqe the tet
Alenorne Used to
Scat s
$cot bea
NCLre
pept
ll N
2
ir
Used tD chonge

~ cd dekfor/

movetle
Gre nedir
tocroer
abecSC Sfa ee
oNl
$ f : or checeino

sqzipwl conpress d le ingeip


A
gzip bcatxt

$urzip! Used to uncompresS the zir ile

set SySte
, Sdabe : osed to sO Culent cote (o)
14date
doele
Mach ,
hosérane sed to view thu ourno the host
hostrome
1shostanoi: dedo shos If adoresS.
s ran:0sel to readnore detaU about Cornmad.
man qrep

who. Ae t hows youu wrelnano Ound view the


ast oqin tine
who
KeAne: Tt Athe Centiat felt f an os. Tie Kenel
Conn ect the syster hodbe to toe arbiottn slw.

The Kenel is essble fo memy roogarnenE


loces s 5 task Haungement sosK arag/
CBatty t w e i s e
tbae
CBaty
SasD os
A Norolitfc kenel3 andiol
Kee-Used in s wjndws..
2> tybid ahe cahe windous
Keinel

t isa oun, kenel for afre


5>Er

witfen in Assernby Lounguag e anol


Vetnel is
Mache code
Lbrgucge

Kene)
ser, )A
ede: xeution one n behal od c
USel mcole!
us rdu Uhet le
Useiflo(ey bitO
Se(steyo DselmOle lrocdla
reut c

C
Kene (bit e)
Hle sytem tonceftt ha ctuyctuee
hke sovctue also relfeied to os tte DiLtery trae
tolthe s a bcutEN that CtoeAmuttiele ie
2bot
binaydr oPtion

chone eaut Kane Ale

flett FTle yfe


4 Tup sfecidl div: Spcl fle -BEV an be relat
link St ink had ink
D torrent diY repen as . Sockeks -Ul fol rletwaiy
e) palent Pipes - Jor communation

t
Jed is
Meuoe lEs Cembina ong, fttition wrh

dowice.

dev
boot ete irt

o t t 2 slands dox Seecnd ectrded tesystemr does


rot have ouhaing deotuteMahuh ntivituout Ae
ye can be drom I6.GrB te 2TB.Ovelajl le syste

DIsk
titono Patiton)-faltene
lutenn
ets Tt Ts Atarcs for thid extended e ysteny
Srom Lire Kelnel 2.4./5 ts as ausibs.
Statrg
The rzaio bereft f et Ts: Joulnaling
suster Se car be kon 2
2TB. ovelal et fe
32T8.redue fle torupén. itisae 3 coun
276 to
casiy Yecovel d
bd
et4: Tt Slards fon fouth ectended ile Syben,Nocmu
slaing
fom inuL keinel 2.6q etq eas ueiaile.
foolividuo fle iZeleon be tlom lbCB to bTB
ovelal eoe exto fAle syster sze s 1£B (oa bytJ.ta
IEB = lo24 PB CPetbyt). PB to24 TB (Jelaby).
D)lectoly con Contain o ro of b, coo subAetoie

File System
Sector Jaunal Bloc o loK
glock
Souna
Tansaoton Dote or oto
Begir Blbc 123Block forTrunsaticd
bs-er Trnsa chod pot do
Begín2 elok lw24id

1
Block

(Suped Gogkeselved hoode Tode


G10T byeiBbcRS
t gwas intoly Trto to tend stooqe Umvty mpoVe
Gaster retoirane. Tt Provide roore eubility in bels
ar Stor e lauge ies s has atvar(s
od doto Stoge It E2. 74 Provid es an
txt2 S
featul es as corraled to
cliril ed ubdi ectody
JAVASCRIPT & MYSQL
What is JavaScript?

 JavaScript was designed to add interactivity to HTML pages


 JavaScript is a scripting language
 A scripting language is a lightweight programming language
 JavaScript is usually embedded directly into HTML pages
 JavaScript is an interpreted language (means that scripts execute without preliminary compilation)
 Everyone can use JavaScript without purchasing a license

Java and JavaScript are two completely different languages in both concept and design!

Java (developed by Sun Microsystems) is a powerful and much more complex programming language - in
the same category as C and C++.

What can a JavaScript Do ?

 JavaScript gives HTML designers a programming tool - HTML authors are normally not
programmers, but JavaScript is a scripting language with a very simple syntax! Almost anyone can
put small "snippets" of code into their HTML pages
 JavaScript can put dynamic text into an HTML page - A JavaScript statement like this:
document.write("<h1>" + name + "</h1>") can write a variable text into an HTML page
 JavaScript can react to events - A JavaScript can be set to execute when something happens,
like when a page has finished loading or when a user clicks on an HTML element
 JavaScript can read and write HTML elements - A JavaScript can read and change the content
of an HTML element
 JavaScript can be used to validate data - A JavaScript can be used to validate form data before
it is submitted to a server. This saves the server from extra processing
 JavaScript can be used to detect the visitor's browser - A JavaScript can be used to detect the
visitor's browser, and - depending on the browser - load another page specifically designed for that
browser.
 JavaScript can be used to create cookies - A JavaScript can be used to store and retrieve
information on the visitor's computer.
JAVASCRIPT & MYSQL

JavaScript Variables
Variables are "containers" for storing information.

JavaScript variables are used to hold values or expressions.

A variable can have a short name, like x, or a more descriptive name, like carname.

Rules for JavaScript variable names:

 Variable names are case sensitive (y and Y are two different variables)
 Variable names must begin with a letter or the underscore character

Note: Because JavaScript is case-sensitive, variable names are case-sensitive.

Example

A variable's value can change during the execution of a script. You can refer to a variable by its name to
display or change its value.

<html>
<body>
<script type="text/javascript">
var firstname;
firstname="Welcome";
document.write(firstname);
document.write("<br />");
firstname="XYZ";
document.write(firstname);
</script>

<p>The script above declares a variable,


assigns a value to it, displays the value, change the value,
and displays the value again.</p>

</body>
</html>

Output :
Welcome
XYZ

The script above declares a variable, assigns a value to it, displays the value, change the value, and
displays the value again.
JAVASCRIPT & MYSQL

Declaring (Creating) JavaScript Variables

Creating variables in JavaScript is most often referred to as "declaring" variables.

You can declare JavaScript variables with the var statement:

var x;
var carname;

After the declaration shown above, the variables are empty (they have no values yet).

However, you can also assign values to the variables when you declare them:

var x=5;
var carname="Scorpio";

After the execution of the statements above, the variable x will hold the value 5, and carname will hold
the value Scorpio.

Note: When you assign a text value to a variable, use quotes around the value.

Assigning Values to Undeclared JavaScript Variables

If you assign values to variables that have not yet been declared, the variables will automatically be
declared.

These statements:

x=5;
carname="Scorpio";

have the same effect as:

var x=5;
var carname="Scorpio";

Redeclaring JavaScript Variables

If you redeclare a JavaScript variable, it will not lose its original value.

var x=5;
var x;
JAVASCRIPT & MYSQL

After the execution of the statements above, the variable x will still have the value of 5. The value of x is
not reset (or cleared) when you redeclare it.

DataTypes

 Numbers - are values that can be processed and calculated. You don't enclose them in quotation
marks. The numbers can be either positive or negative.
 Strings - are a series of letters and numbers enclosed in quotation marks. JavaScript uses the string
literally; it doesn't process it. You'll use strings for text you want displayed or values you want
passed along.
 Boolean (true/false) - lets you evaluate whether a condition meets or does not meet specified
criteria.
 Null - is an empty value. null is not the same as 0 -- 0 is a real, calculable number, whereas null is
the absence of any value.

Data Types

TYPE EXAMPLE
Numbers Any number, such as 17, 21, or 54e7
Strings "Greetings!" or "Fun"

Boolean Either true or false

Null A special keyword for exactly that – the null value (that is, nothing)
JAVASCRIPT & MYSQL

JavaScript Arithmetic

As with algebra, you can do arithmetic operations with JavaScript variables:

y=x-5;
z=y+5;

JavaScript Operators
The operator = is used to assign values.

The operator + is used to add values.

The assignment operator = is used to assign values to JavaScript variables.

The arithmetic operator + is used to add values together.

y=5;
z=2;
x=y+z;

The value of x, after the execution of the statements above is 7.

JavaScript Arithmetic Operators

Arithmetic operators are used to perform arithmetic between variables and/or values.

Given that y=5, the table below explains the arithmetic operators:

Operator Description Example Result


+ Addition x=y+2 x=7
- Subtraction x=y-2 x=3
* Multiplication x=y*2 x=10
/ Division x=y/2 x=2.5
% Modulus (division remainder) x=y%2 x=1
++ Increment x=++y x=6
-- Decrement x=--y x=4

JavaScript Assignment Operators


JAVASCRIPT & MYSQL
Assignment operators are used to assign values to JavaScript variables.

Given that x=10 and y=5, the table below explains the assignment operators:

Operator Example Same As Result


= x=y x=5
+= x+=y x=x+y x=15
-= x-=y x=x-y x=5
*= x*=y x=x*y x=50
/= x/=y x=x/y x=2
%= x%=y x=x%y x=0

The + Operator Used on Strings

The + operator can also be used to add string variables or text values together.

To add two or more string variables together, use the + operator.

txt1="What a very";
txt2="nice day";
txt3=txt1+txt2;
JAVASCRIPT & MYSQL

After the execution of the statements above, the variable txt3 contains "What a verynice day".

To add a space between the two strings, insert a space into one of the strings:

txt1="What a very ";


txt2="nice day";
txt3=txt1+txt2;

or insert a space into the expression:

txt1="What a very";
txt2="nice day";
txt3=txt1+" "+txt2;

After the execution of the statements above, the variable txt3 contains:

"What a very nice day"

Adding Strings and Numbers

Look at these examples:

x=5+5;
document.write(x);

x="5"+"5";
document.write(x);

x=5+"5";
document.write(x);

x="5"+5;
document.write(x);

The rule is:

If you add a number and a string, the result will be a string.

JavaScript Comparison and Logical Operators

Comparison and Logical operators are used to test for true or false.
JAVASCRIPT & MYSQL

Comparison Operators

Comparison operators are used in logical statements to determine equality or difference between variables
or values.

Given that x=5, the table below explains the comparison operators:

Operator Description Example


== is equal to x==8 is false
=== is exactly equal to (value and type) x===5 is true
x==="5" is false
!= is not equal x!=8 is true
> is greater than x>8 is false
< is less than x<8 is true
>= is greater than or equal to x>=8 is false
<= is less than or equal to x<=8 is true

How Can it be Used

Comparison operators can be used in conditional statements to compare values and take action depending
on the result:

if (age<18) document.write("Too young");

You will learn more about the use of conditional statements in the next chapter of this tutorial.

Logical Operators

Logical operators are used to determine the logic between variables or values.

Given that x=6 and y=3, the table below explains the logical operators:

Operator Description Example


&& and (x < 10 && y > 1) is true
|| or (x==5 || y==5) is false
! not !(x==y) is true

Conditional Operator

JavaScript also contains a conditional operator that assigns a value to a variable based on some condition.
JAVASCRIPT & MYSQL

Syntax
variablename=(condition)?value1:value2

Example
greeting=(visitor=="PRES")?"Dear President ":"Dear ";

If the variable visitor has the value of "PRES", then the variable greeting will be assigned the value
"Dear President " else it will be assigned "Dear".

Conditional Statements

Very often when you write code, you want to perform different actions for different decisions. You can
use conditional statements in your code to do this.

In JavaScript we have the following conditional statements:

 if statement - use this statement if you want to execute some code only if a specified condition is
true
 if...else statement - use this statement if you want to execute some code if the condition is true
and another code if the condition is false
 if...else if.... else statement - use this statement if you want to select one of many blocks of code to
be executed
 switch statement - use this statement if you want to select one of many blocks of code to be
executed

If Statement

You should use the if statement if you want to execute some code only if a specified condition is true.

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

Note that if is written in lowercase letters. Using uppercase letters (IF) will generate a JavaScript error!

Example 1
<script type="text/javascript">
//Write a "Good morning" greeting if
//the time is less than 10
var d=new Date();
var time=d.getHours();
JAVASCRIPT & MYSQL

if (time<10)
{
document.write("<b>Good morning</b>");
}
</script>

Example 2
<script type="text/javascript">
//Write "Lunch-time!" if the time is 11
var d=new Date();
var time=d.getHours();

if (time==11)
{
document.write("<b>Lunch-time!</b>");
}
</script>

Note: When comparing variables you must always use two equals signs next to each other (==)!

Notice that there is no ..else.. in this syntax. You just tell the code to execute some code only if the
specified condition is true.

If...else Statement

If you want to execute some code if a condition is true and another code if the condition is not true, use
the if ...else statement.

Syntax

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

Example
<script type="text/javascript">
//If the time is less than 10,
//you will get a "Good morning" greeting.
//Otherwise you will get a "Good day" greeting.
var d = new Date();
JAVASCRIPT & MYSQL

var time = d.getHours();

if (time < 10)


{
document.write("Good morning!");
}
else
{
document.write("Good day!");
}
</script>

If...else if...else Statement

You should use the if....else if...else statement if you want to select one of many sets of lines to execute.

Syntax
if (condition1)
{
code to be executed if condition1 is true
}
else if (condition2)
{
code to be executed if condition2 is true
}
else
{
code to be executed if condition1 and
condition2 are not true
}

Example
<script type="text/javascript">
var d = new Date()
var time = d.getHours()
if (time<10)
{
document.write("<b>Good morning</b>");
}
else if (time>10 && time<16)
{
document.write("<b>Good day</b>");
}
else
JAVASCRIPT & MYSQL

{
document.write("<b>Hello World!</b>");
}
</script>

The JavaScript Switch Statement

You should use the switch statement if you want to select one of many blocks of code to be executed.

Syntax
switch(n)
{
case 1:
execute code block 1
break;
case 2:
execute code block 2
break;
default:
code to be executed if n is
different from case 1 and 2
}

This is how it works: First we have a single expression n (most often a variable), that is evaluated once.
The value of the expression is then compared with the values for each case in the structure. If there is a
match, the block of code associated with that case is executed. Use break to prevent the code from
running into the next case automatically.

Example
<script type="text/javascript">
//You will receive a different greeting based
//on what day it is. Note that Sunday=0,
//Monday=1, Tuesday=2, etc.
var d=new Date();
theDay=d.getDay();
switch (theDay)
{
case 5:
document.write("Finally Friday");
break;
case 6:
document.write("Super Saturday");
break;
case 0:
document.write("Sleepy Sunday");
JAVASCRIPT & MYSQL

break;
default:
document.write("I'm looking forward to this weekend!");
}
</script>

JavaScript Controlling(Looping) Statements

Loops in JavaScript are used to execute the same block of code a specified number of times or while
a specified condition is true.

JavaScript Loops

Very often when you write code, you want the same block of code to run over and over again in a row.
Instead of adding several almost equal lines in a script we can use loops to perform a task like this.

In JavaScript there are two different kind of loops:

 for - loops through a block of code a specified number of times


 while - loops through a block of code while a specified condition is true

The for Loop

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

Syntax

for (var=startvalue;var<=endvalue;var=var+increment)
{
code to be executed
}

Example

Explanation: The example below defines a loop that starts with i=0. The loop will continue to run as long
as i is less than, or equal to 10. i will increase by 1 each time the loop runs.

Note: The increment parameter could also be negative, and the <= could be any comparing statement.

<html>
<body>
<script type="text/javascript">
var i=0;
for (i=0;i<=10;i++)
{
JAVASCRIPT & MYSQL

document.write("The number is " + i);


document.write("<br />");
}
</script>
</body>
</html>

Result

The number is 0
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
The number is 6
The number is 7
The number is 8
The number is 9
The number is 10

JavaScript While Loop

Loops in JavaScript are used to execute the same block of code a specified number of times or while
a specified condition is true.

The while loop

The while loop is used when you want the loop to execute and continue executing while the specified
condition is true.

while (var<=endvalue)
{
code to be executed
}

Note: The <= could be any comparing statement.

Example

Explanation: The example below defines a loop that starts with i=0. The loop will continue to run as long
as i is less than, or equal to 10. i will increase by 1 each time the loop runs.

<html>
JAVASCRIPT & MYSQL

<body>
<script type="text/javascript">
var i=0;
while (i<=10)
{
document.write("The number is " + i);
document.write("<br />");
i=i+1;
}
</script>
</body>
</html>

Result

The number is 0
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
The number is 6
The number is 7
The number is 8
The number is 9
The number is 10

The do...while Loop

The do...while loop is a variant of the while loop. This loop will always execute a block of code ONCE,
and then it will repeat the loop as long as the specified condition is true. This loop will always be
executed at least once, even if the condition is false, because the code is executed before the condition is
tested.

do
{
code to be executed
}
while (var<=endvalue);

Example

<html>
<body>
<script type="text/javascript">
JAVASCRIPT Notes

var i=0;
do
{
document.write("The number is " + i);
document.write("<br />");
i=i+1;
}
while (i<0);
</script>
</body>
</html>

Result

The number is 0

JavaScript Break and Continue


There are two special statements that can be used inside loops: break and continue.

JavaScript break and continue Statements

There are two special statements that can be used inside loops: break and continue.

Break

The break command will break the loop and continue executing the code that follows after the loop (if
any).

Example

<html>
<body>
<script type="text/javascript">
var i=0;
for (i=0;i<=10;i++)
{
if (i==3)
{
break;
}
document.write("The number is " + i);
document.write("<br />");
}
</script>
</body>
JAVASCRIPT& MYSQL
Notes
</html>

Result

The number is 0
The number is 1
The number is 2

Continue

The continue command will break the current loop and continue with the next value.

Example

<html>
<body>
<script type="text/javascript">
var i=0
for (i=0;i<=10;i++)
{
if (i==3)
{
continue;
}
document.write("The number is " + i);
document.write("<br />");
}
</script>
</body>
</html>

Result

The number is 0
The number is 1
The number is 2
The number is 4
The number is 5
The number is 6
The number is 7
The number is 8
The number is 9
The number is 10
JAVASCRIPT& MYSQL
Notes
MYSQL
It is freely available open source Relational Database Management System (RDBMS) that uses
Structured Query Language(SQL). In MySQL database , information is stored in Tables. A
single MySQL database can contain many tables at once and store thousands of individual
records.
The create database Statement
The general syntax is as follows:
create database database_name
From the MySQL command-line client, you can simply type in the following command:
mysql> create database my_database;

The use database Statement


mysql>use database_name

The create table Statement


Once you have created and selected a database, you are ready to create a table.
The basic create table statement is fairly simple and takes this basic form:
create table table_name ( column_name_1 column_type column_attributes,
column_name_2 column_type column_attributes, primary key (column_name),
index index_name(column_name) )type=table_type

Example:
create table topics ( topic_id integer not null auto_increment, parent_id integer default 0 not
null, root_id integer default 0, name varchar(255), description text null, create_dt timestamp,
modify_dt timestamp, author varchar(255) null, author_host varchar(255) null, primary
key(topic_id), index my_index(parent_id) )type=myisam;

Using the show Command


You can get a list of databases by issuing the show databases command:
mysql> show databases;
+----------+
| Database |
+----------+
| mysql |
| store |
| test |
+----------+
3 rows in set (0.14 sec)
show tables After you are connected to a specific database, you can view the tables that make
up the database by running the show tables command:
JAVASCRIPT& MYSQL
Notes
mysql> show tables;
+-----------------+
| Tables_in_store |
+-----------------+
| addresses |
| formats |
| items_for_sale |
| order_items |
| orders |
| places |
| products |
| users |
+-----------------+
8 rows in set (0.01 sec)

The insert Statement


You will use the insert statement to place rows of data into your tables.
The basic form of the SQL insert statement is as follows:
Insert into tablename ( column1 [, column2 [, column3 [, ...] ] ] ) values ( value1 [,
value2 [, value3 [, ...] ] ] )

Text strings must be surrounded by single quote marks (‘), or double-quote marks (‘’) if you’re
not running in ANSI mode.
For example:
insert into table_name (text_col, int_col) values (‘hello world’, 1)
The update Statement
update table_name set col_1=value1, col_2=value_2 where col=value
For Example:
update folks set fname=’Vito’ where id=2;
The delete Statement
The delete statement removes a row or multiple rows from a table.
The syntax is as follows:
delete from table_where where-clause
For Example:
delete from folks where id=1;
The Basic select Statement
select column_1, column_2, column_3 from table_name
Or
select * from table_name
The where clause
The where clause limits the rows that are returned from your query.
select * from users where userid = 2;
JAVASCRIPT& MYSQL
Notes

The DISTINCT Statement


SELECT DISTINCT column1, column2, ...
FROM table_name;
For Example
SELECT DISTINCT Country FROM Customers;
USING like
Two wildcard characters are available: the underscore (_) and the percent sign (%). The
underscore stands for a single character; the percent sign represents any number of characters
For Example:
select * from users where fname like ‘Dan%’;
order by
select * from users order by lname, fname;
MySQL DELETE Statement
The DELETE statement is used to delete existing records in a table
DELETE Syntax

DELETE FROM table_name WHERE condition;

For Example:

DELETE FROM Customers WHERE CustomerName='Alfreds Futterkiste';


UNIT–IV
PHP
IntroductiontoPHP&Features
PHPScripts
DataTypes
Variables
Operators
ControlStructures
WorkingwithArrays
Functions
WorkingwithFiles
WorkingwithDatabases

IntroductiontoPHP&Features

PHPisaserverscriptinglanguage,andapowerfultoolformakingdynamicandinteractive Web pages.

PHPisawidely-used,free,andefficientalternativetocompetitorssuchasMicrosoft'sASP.

Example
<html>
<body>
<?php
echo"MyfirstPHP
script!"; ?>
</body>
</html>

WhatYouShouldAlreadyKnow

Beforeyoucontinueyoushouldhaveabasicunderstandingofthefollowing:

• HTML
• CSS
• JavaScript

WhatisPHP?
• PHPisanacronymfor"PHP:HypertextPreprocessor"
• PHPisawidely-used,opensourcescriptinglanguage
• PHPscriptsareexecutedontheserver
• PHPisfreetodownloadanduse

WhatisaPHPFile?

• PHPfilescancontaintext,HTML,CSS,JavaScript,andPHPcode
• PHPcodeareexecutedontheserver,andtheresultisreturnedtothebrowser as plain
HTML
• PHPfileshaveextension".php"

WhatCanPHP Do?

• PHPcangeneratedynamicpagecontent
• PHPcancreate,open,read,write,delete,andclosefilesontheserver
• PHPcancollectformdata
• PHPcansendandreceivecookies
• PHPcanadd,delete,modifydatainyourdatabase
• PHPcanbeusedtocontroluser-access
• PHPcanencryptdata

WithPHPyouarenotlimitedtooutputHTML.Youcanoutputimages,PDFfiles,and even
Flash movies. You can also output any text, such as XHTML and XML.

WhyPHP?

• PHPrunsonvariousplatforms(Windows,Linux,Unix,MacOSX,etc.)
• PHPiscompatiblewithalmostallserversusedtoday(Apache,IIS,etc.)
• PHPsupportsawiderangeofdatabases
• PHPisfree.DownloaditfromtheofficialPHPresource:www.php.net
• PHPiseasytolearnandrunsefficientlyontheserverside

TostartusingPHP, youcan:

• FindawebhostwithPHPandMySQLsupport
• InstallawebserveronyourownPC,andtheninstallPHPandMySQL

UseaWebHostwithPHP Support

• IfyourserverhasactivatedsupportforPHPyoudonotneedtodoanything.
• Justcreatesome.phpfiles,placetheminyourwebdirectory,andtheserverwill
automatically parse them for you.
• Youdonotneedtocompileanythingorinstallanyextratools.
• BecausePHPisfree,mostwebhostsofferPHPsupport.
• SetUpPHPonYourOwnPC
However,ifyourserverdoesnotsupportPHP, youmust:

• installa web server


• installPHP
• installadatabase,suchas MySQL

PHP Scripts

BasicPHPSyntax

• APHPscriptcanbeplacedanywhereinthedocument.
• APHPscriptstartswith <?phpandendswith?>:

<?php
//PHPcodegoes here
?>

Example
<html>
<body>

<h1>MyfirstPHP page</h1>

<?php
echo"HelloWorld!";
?>

</body>
</html>
• PHPstatementsendwithasemicolon(;)

CommentsinPHP

AcommentinPHPcodeisalinethatisnot read/executedaspartoftheprogram.Its only


purpose is to be read by someone who is looking at the code.

Commentscanbeusedto:

• Letothersunderstandwhatyouaredoing
• Remind yourself of what you did - Most programmers have experienced coming
back to their own work a year or two later and having to re-figure out what they
did. Comments can remind you of what you were thinking when you wrote the
code
Example
<html>
<body>
<?php
//Thisisasingle-linecomment
#Thisisalsoasingle-line comment
/*
Thisisamultiple-linescomment
block that spans over multiple
lines
*/
//Youcanalsousecommentstoleaveoutpartsofacodeline
$x=5/*+15*/+5; echo
$x;?>
</body>
</html>

Example
<html>
<body>
<?php
ECHO"HelloWorld!<br>";
echo "Hello World!<br>";
EcHo "Hello World!<br>";
?>
</body>
</html>

In the example below, only the first statement will display the value of the $color
variable(thisisbecause$color,$COLOR,and$coLORaretreatedasthreedifferent
variables):

Example
<html>
<body>
<?php
$color="red";
echo"Mycaris".$color."<br>";
echo "My house is ". $COLOR .
"<br>";echo"Myboatis".$coLOR.
"<br>"; ?>
</body>
</html>

DataTypes

• Variablescanstoredataofdifferent types,anddifferentdatatypescando
different things.

PHPsupportsthefollowingdata types:

• String
• Integer
• Float(floatingpointnumbers-alsocalleddouble)
• Boolean
• Array
• Object
• NULL
• Resource

PHPString

• Astringisasequenceofcharacters,like"Helloworld!".
• Astringcanbeanytextinsidequotes.Youcanusesingleordoublequotes:

Example

<html>
<body>
<?php
$x="Hello world!";
$y='Helloworld!';
echo $x;
echo"<br>";
echo $y;
?>
</body>
</html>

OUTPUT:

Helloworld!
Helloworld!
String Functions

• GetTheLengthof aString
• ThePHPstrlen()functionreturnsthelengthofastring.
• Theexamplebelowreturnsthelengthofthestring"Helloworld!":
Example

<html>
<body>
<?php
echostrlen("Hello
world!"); ?>
</body>
</html>

OUPUT:

12

CountTheNumberofWordsinaString

ThePHPstr_word_count()functioncountsthenumberofwordsinastring:

Example

<html>
<body>
<?php
echostr_word_count("Helloworld!");
?>
</body>
</html>

OUPUT:

ReverseaString

• ThePHPstrrev()functionreversesastring:

Example

<html>
<body>
<?php
echostrrev("Helloworld!");
?>
</body>
</html>

OUTPUT:

!dlrowolleH

SearchForaSpecificTextWithina String

• ThePHPstrpos()functionsearchesforaspecifictextwithinastring.
• Ifamatchisfound,thefunctionreturnsthecharacterpositionofthefirstmatch.If no
match is found, it will return FALSE.
• Theexamplebelowsearchesforthe text"world"inthestring"Helloworld!":

Example

<html>
<body>
<?php
echostrpos("Helloworld!","world");
?>
</body>
</html>

OUPUT:

ReplaceTextWithina String

•ThePHPstr_replace()functionreplacessomecharacterswithsomeother
characters in a string.
• Theexamplebelowreplacesthetext"world"with"Dolly":
Example

<html>
<body>
<?php
echostr_replace("world","Dolly","Helloworld!");
?>
</body>
</html>
OUPUT:

HelloDolly!

PHPInteger

Anintegerdatatypeisanon-decimalnumberbetween -2,147,483,648and 2,147,483,647.

Rulesforintegers:

• Anintegermusthaveatleastonedigit
• Anintegermustnothaveadecimal point
• Anintegercanbeeitherpositiveor negative
• Integerscanbespecifiedinthreeformats:decimal(10-based),hexadecimal(16-
based - prefixed with 0x) or octal (8-based - prefixed with 0)
• Inthefollowingexample$xisaninteger.ThePHPvar_dump()function
returns the data type and value:

Example

<html>
<body>
<?php
$x= 5985;
var_dump($x);
?>
</body>
</html>

OUTPUT:

int(5985)

PHPFloat

• Afloat(floatingpointnumber)isanumberwithadecimalpointora numberin
exponential form.
• Inthefollowingexample$xisafloat.The PHPvar_dump()functionreturnsthe data
type and value:

Example

<html>
<body>
<?php
$x= 10.365;
var_dump($x);
?>
</body>
</html>

OUTPUT:

float(10.365)

PHPBoolean

ABooleanrepresentstwopossiblestates:TRUEorFALSE.

$x= true;
$y= false;

Booleansareoftenusedinconditionaltesting.Youwilllearnmoreaboutconditional testing in
a later chapter of this tutorial.

PHP Array

• Anarraystoresmultiplevaluesinonesinglevariable:
• Anarrayisaspecialvariable,whichcanholdmorethanonevalue atatime.
• Ifyouhavealistofitems(alistofcarnames,forexample),storingthecars in single
variables could look like this:

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

• However,whatifyouwanttoloopthroughthecarsandfindaspecificone? And
what if you had not 3 cars, but 300?
• Thesolutionistocreateanarray!
• Anarraycanholdmanyvaluesunderasinglename,andyoucanaccessthe values
by referring to an index number.

Example
<html>
<body>
<?php
$cars=array("Volvo","BMW","Toyota");
echo"Ilike".$cars[0]. ",".$cars[1] ." and".$cars[2].".";
?>
</body>
</html>
OUTPUT:

IlikeVolvo,BMWandToyota.
CreateanArrayin PHP

• InPHP,the array()functionisusedtocreateanarray:

array();

InPHP,therearethreetypesofarrays:

• Indexedarrays-Arrayswithanumericindex
• Associativearrays-Arrayswithnamedkeys
• Multidimensionalarrays -Arrayscontainingoneormorearrays

Variables

• Variablesare"containers"forstoringinformation.
• Creating(Declaring)PHPVariables

• InPHP,avariablestartswiththe$sign,followedbythenameofthevariable:

Example
<html>
<body>
<?php
$txt="Helloworld!";
$x=5; Output:
$y=10.5;
Helloworld!
echo$txt; 5
echo"<br>"; 10.5
echo$x;
echo"<br>";
echo$y;
?>

</body>
</html>
After the execution of the statements above, the variable $txt will hold the value Hello
world!,thevariable $xwillholdthevalue 5,andthevariable$ywillholdthevalue 10.5.

Note:Whenyouassignatextvaluetoavariable,putquotesaroundthe value.

Note:Unlikeotherprogramminglanguages,PHPhasnocommandfordeclaringa variable. It
is created the moment you first assign a value to it.

RulesforPHPvariables:

Avariablecanhaveashortname(likexandy)oramoredescriptivename(age, carname,
total_volume).

• Avariablestartswiththe$sign,followedbythenameofthevariable
• Avariablenamemuststartwithaletterortheunderscorecharacter
• Avariablenamecannotstartwitha number
• Avariablenamecanonlycontainalpha-numericcharactersandunderscores(A- z, 0-
9, and _ )
• Variablenamesarecase-sensitive($ageand$AGEaretwodifferentvariables)

Output Variables

• ThePHPechostatementisoftenusedtooutputdatatothescreen.

Thefollowingexamplewillshowhowtooutputtextanda variable:

Example

<html> Output:
<body>
<?php IloveW3Schools.com!
$txt="W3Schools.com"; echo
"I love $txt!";
?>
</body>
</html>

Example

<html>
<body>
<?php
Output:
$txt="W3Schools.com"; echo
"I love ". $txt . "!"; IloveW3Schools.com!
?>
</body>
</html>
Example

<html>
<body>
<?php
$x=5; Output:
$y=4;
echo$x+$y; 9
?>
</body>
</html>

PHPVariablesScope

• InPHP,variablescanbedeclaredanywhereinthescript.
• Thescopeofavariableisthepartofthescriptwherethevariablecanbe
referenced/used.

PHPhasthreedifferentvariablescopes:

• local
• global
• static

GlobalandLocal Scope

Avariabledeclared outsideafunctionhasaGLOBALSCOPEandcanonlybe accessed


outside a function:

Example

<html>
<body>
<?php
$x=5;//globalscope
function myTest() {
//usingxinsidethisfunctionwillgenerateanerror echo
"<p>Variable x inside function is: $x</p>";
}
myTest();
echo"<p>Variablexoutsidefunctionis:
$x</p>";?>
</body>
</html>
OUTPUT:

Variablexinsidefunctionis:

Variablexoutsidefunctionis:5

AvariabledeclaredwithinafunctionhasaLOCALSCOPEandcanonlybeaccessed within
that function:

Example
<html>
<body>
<?php
functionmyTest(){
$x=5; //localscope
echo"<p>Variablexinsidefunctionis: $x</p>";
}
myTest();
//usingxoutsidethefunctionwillgeneratean error
echo "<p>Variable x outside function is:
$x</p>";?>
</body>
</html>

OUTPUT:

Variablexinsidefunctionis:5
Variable x outside function is:

TheglobalKeyword

• Theglobalkeywordisusedtoaccessaglobalvariablefromwithinafunction.
• Todothis,usethe globalkeywordbeforethevariables(insidethefunction):

Example

<html>
<body> Output:
<?php
$x= 5; 15
$y= 10;
functionmyTest(){
global$x,$y;$y
=$x+ $y;
}
myTest();//run function
echo$y;//outputthenewvaluefor variable
$y?>
</body>
</html>
ThestaticKeyword

Normally, when a function is completed/executed, all of its variables are deleted.


However, sometimes we want a local variable NOT to be deleted. We need it for a
further job.

Todothis,usethestatickeywordwhenyoufirstdeclarethevariable:

Example
<html>
<body>
<?php
Output:
functionmyTest(){
static $x = 0;
0
echo $x;
$x++; 1
}
myTest(); 2
echo"<br>";
myTest();
echo"<br>";
myTest();
?>
</body>
</html>
echo and printStatements

• InPHPtherearetwobasicwaystogetoutput:echoandprint.
• In this tutorial we use echo (and print) in almost every example. So, this chapter
contains a little more info about those two output statements.
• echoand print are more or less the same. They are both used to output data to
the screen.
• The differencesare small: echohasno return value while printhas a return value of
1 so it can be used in expressions. echo can take multiple parameters (although
such usage is rare) while printcan take one argument. echois marginally faster
than print.
echo Statement

Theechostatementcanbeusedwithorwithoutparentheses:echoorecho().

DisplayText

Thefollowingexampleshowshowtooutputtext withthe echocommand(noticethatthe text can


contain HTML markup):

Example

<html>
<body>
<?php
echo"<h2>PHPisFun!</h2>"; echo
"Hello world!<br>";
echo"I'mabouttolearn PHP!<br>";
echo"This","string","was","made","withmultiple
parameters."; ?>
</body>
</html>

OUTPUT:

PHPisFun!
Helloworld!
I'mabouttolearn PHP!
Thisstringwasmadewith multiple parameters.

DisplayVariables

Thefollowingexampleshowshowtooutputtextandvariableswiththeechostatement:

Example

<html>
<body>
<?php
$txt1="LearnPHP";$txt2
="W3Schools.com";$x= 5;
$y=4;
echo"<h2>".$txt1. "</h2>";
echo"StudyPHPat".$txt2."<br>";
echo$x+$y;
?>
</body>
</html>

OUTPUT:
LearnPHP
Study PHP at
W3Schools.com9

ThePHPprint Statement

• Theprintstatementcanbeusedwithorwithoutparentheses:printorprint().

DisplayText

Thefollowingexampleshowshowtooutputtext withthe printcommand(noticethatthe text can


contain HTML markup):

Example

<html>
<body>
<?php
print"<h2>PHPisFun!</h2>";
print "Hello world!<br>";
print"I'mabouttolearn PHP!";
?>
</body>
</html>

OUTPUT:

PHPisFun!
Helloworld!
I'mabouttolearn PHP!

DisplayVariables

Thefollowingexampleshowshowtooutputtextandvariableswiththeprintstatement:

Example
<html>
<body>
<?php
$txt1="LearnPHP";
$txt2="W3Schools.com";
$x= 5;
$y=4;
print"<h2>".$txt1."</h2>";
print"StudyPHPat".$txt2."<br>"; print
$x +
$y;?>
</body>
</html>

OUTPUT:

LearnPHP
Study PHP at
W3Schools.com9

PHPObject

• Anobjectisadatatypewhichstoresdataandinformationonhowtoprocessthat data.
• InPHP,anobjectmustbeexplicitly declared.
• Firstwemustdeclareaclassofobject.Forthis, weusetheclasskeyword.A class is
a structure that can contain properties andmethods:

Example

<html>
<body>
<?php
classCar{
functionCar(){ $this-
>model ="VW";
}
}
//createanobject
$herbie=newCar();
// show object
propertiesecho
$herbie->model;?>
</body>
</html>
OUPUT:

VW

PHPNULLValue

• Nullisaspecialdatatypewhichcanhaveonlyonevalue:NULL.
• AvariableofdatatypeNULLisavariablethathasnovalueassignedtoit.
• Ifavariableiscreatedwithoutavalue,itisautomaticallyassignedavalueof NULL.
• VariablescanalsobeemptiedbysettingthevaluetoNULL:

Example

<html>
<body>
<?php
$x="Hello world!";
$x = null;
var_dump($x);
?>
</body>
</html>

OUTPUT:

NULL

Constants

• Constantsarelikevariablesexceptthatoncetheyaredefinedtheycannotbe
changed or undefined.
• PHPConstants
• Aconstantisanidentifier(name)forasimplevalue.Thevaluecannotbe
changed during the script.
• Avalidconstantnamestartswithaletterorunderscore(no$signbeforethe
constant name).

Note:Unlikevariables,constantsareautomaticallyglobalacrosstheentirescript.

CreateaPHPConstant

• Tocreateaconstant,usethedefine()function.

Syntax
define(name,value,case-insensitive)

Parameters:

• name:Specifiesthenameoftheconstant
• value:Specifiesthevalueoftheconstant
• case-insensitive:Specifieswhethertheconstantnameshouldbecase-
insensitive. Default is false

Theexamplebelowcreatesaconstantwitha case-sensitivename:

Example

<html>
<body>
<?php
//case-sensitiveconstant name
define("GREETING", "Welcome to
W3Schools.com!");echoGREETING;
?>
</body>
</html>

OUTPUT:

WelcometoW3Schools.com!

Theexamplebelowcreatesaconstantwitha case-insensitivename:

Example

<html>
<body>
<?php
//case-insensitiveconstant name
define("GREETING","WelcometoW3Schools.com!",true);
echo greeting;
?>
</body>
</html>

OUPUT:

WelcometoW3Schools.com!
ConstantsareGlobal

• Constantsareautomaticallyglobalandcanbeusedacrosstheentirescript.
• Theexamplebelowusesaconstantinsideafunction,evenifitisdefinedoutside the
function:

Example

<html>
<body>
<?php
define("GREETING", "Welcome to
W3Schools.com!");functionmyTest(){
echoGREETING;
}
myTest();
?>
</body>
</html>

OUPUT:

WelcometoW3Schools.com!

PHPOperators

Operatorsareusedtoperformoperationsonvariablesand values.

PHPdividestheoperatorsinthefollowinggroups:

• Arithmeticoperators
• Assignmentoperators
• Comparisonoperators
• Increment/Decrementoperators
• Logicaloperators
• Stringoperators
• Arrayoperators

PHPArithmeticOperators

• ThePHParithmeticoperatorsareusedwith numericvaluestoperformcommon
arithmetical operations, such as addition, subtraction, multiplication etc.
Operator Name Example Result

+ Addition $x+$y Sumof $xand$y

- Subtraction $x-$y Differenceof$xand$y

* Multiplication $x* $y Productof$xand$y

/ Division $x/$y Quotientof $xand$y

% Modulus $x%$y Remainderof$xdividedby$y

** Exponentiation $x**$y Resultofraising$xtothe$y'thpower


(IntroducedinPHP5.6)

PHPAssignmentOperators

• ThePHPassignmentoperatorsareusedwithnumericvaluestowriteavalue to a
variable.
• ThebasicassignmentoperatorinPHPis"=".Itmeansthattheleftoperand gets
set to the value of the assignment expression on the right.

Assignment Sameas...Description
x=y x=y Theleftoperandgetssettothevalueofthe expression
ontheright

x+= y x=x+y Addition

x-=y x=x-y Subtraction

x*=y x=x*y Multiplication

x/=y x=x/ y Division

x%= y x=x% y Modulus

PHPComparisonOperators

• ThePHPcomparisonoperatorsareusedtocomparetwovalues(number or
string):

Operator Name Example Result

== Equal $x==$y Returnstrueif$xis equalto$y


=== Identical $x===$y Returnstrueif$xisequalto$y,andtheyareof
thesametype

!= Notequal $x!=$y Returnstrueif$xisnotequalto$y

<> Notequal $x<>$y Returnstrueif$xisnotequalto$y

!== Notidentical $x!==$y Returnstrueif$xisnotequalto$y,orthey are


notof thesametype

> Greaterthan $x>$y Returnstrueif$xisgreaterthan$y

< Lessthan $x<$y Returnstrueif$xislessthan$y

>= Greaterthanor $x>=$y Returnstrueif$xisgreaterthanorequalto$y


equalto

<= Lessthanorequal $x<=$y Returnstrueif$xislessthanorequalto$y


to

PHPIncrement/DecrementOperators

• ThePHPincrementoperatorsareusedtoincrementavariable'svalue.
• ThePHPdecrementoperatorsareusedtodecrementavariable'svalue.
Operator Name Description

++$x Pre-increment Increments$xbyone,thenreturns$x

$x++ Post-increment Returns$x,thenincrements$xbyone

--$x Pre-decrement Decrements$xbyone,thenreturns$x

$x-- Post-decrement Returns$x,thendecrements$xbyone

PHPLogicalOperators

• ThePHPlogicaloperatorsareusedtocombineconditionalstatements.

Operator Name Example Result

And And $xand $y Trueifboth$xand$yaretrue

Or Or $xor $y Trueifeither$xor$yistrue

Xor Xor $xxor$y Trueifeither$xor$yistrue,butnot


both
&& And $x&&$y Trueifboth$xand$yaretrue

|| Or $x||$y Trueifeither$xor$yistrue

! Not !$x Trueif$xisnottrue

PHPString Operators

• PHPhastwooperatorsthatarespeciallydesignedforstrings.

Operator Name Example Result

. Concatenation $txt1.$txt2 Concatenationof$txt1and


$txt2

.= Concatenation $txt1.=$txt2Appends$txt2to $txt1


assignment

PHPArrayOperators

• ThePHParrayoperatorsareusedtocomparearrays.

Operator Name ExampleResult

+ Union $x+$y Unionof $xand$y


== Equality $x==$y Returnstrueif$xand$yhavethesamekey/value pairs

=== Identity $x === Returnstrueif$xand$yhavethesamekey/value pairs in


$y the same order and of the same types

!= Inequality $x!=$y Returnstrueif$xisnotequalto$y

<> Inequality $x<>$y Returnstrueif$xisnotequalto$y

!== Non- $x!==$y Returnstrueif$xisnotidenticalto$y


identity

PHPConditionalStatements

• Very often when you write code, you want to perform different actions for
differentconditions.Youcanuseconditionalstatementsinyourcodetodothis.

InPHPwehavethefollowingconditionalstatements:

• ifstatement-executessomecodeifoneconditionistrue
• if...elsestatement-executessomecodeifaconditionistrueandanothercode if that
condition is false
• if...elseif.... elsestatement-executesdifferentcodesformorethantwoconditions
• switchstatement -selectsoneofmanyblocksof codetobeexecuted

TheifStatement

• Theifstatementexecutessomecodeifoneconditionistrue.

Syntax
if(condition){
codetobeexecutedifconditionistrue;
}

Theexamplebelowwilloutput"Haveagoodday!"ifthecurrenttime(HOUR)is less
than 20:

Example

<html>
<body>
<?php
$t= date("H");
if($t<"20"){
echo"Haveagoodday!";
}
?>
</body>
</html>

OUTPUT:

Haveagoodday!

Theif...elseStatement

The if ... elsestatementexecutessomecodeifaconditionistrueandanothercode


ifthatconditionisfalse.

Syntax
if(condition){
codetobeexecutedifconditionistrue;
}else {
codetobeexecutedifconditionisfalse;
}

Theexamplebelowwilloutput"Haveagoodday!"ifthecurrenttimeislessthan20, and "Have


a good night!" otherwise:

Example

<html>
<body>
<?php
$t= date("H");
if($t<"20"){
echo"Haveagoodday!";
}else {
echo"Haveagoodnight!";
}
?>
</body>
</html>

OUTPUT:

Haveagoodday!

Theif... elseif ....elseStatement

The if....elseif... else statementexecutesdifferentcodesformorethantwo conditions.

Syntax
if(condition){
codetobeexecutedifthisconditionistrue;
}elseif(condition){
codetobeexecutedifthisconditionistrue;
}else {
codetobeexecutedifallconditionsarefalse;
}

The example below will output "Have a good morning!" if the currenttime 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

<html>
<body>
<?php
$t= date("H");
echo"<p>Thehour(oftheserver)is".$t;
echo",andwillgivethefollowingmessage:</p>"; if
($t <"10") {
echo"Haveagoodmorning!";
}elseif($t<"20"){
echo"Haveagoodday!";
}else {
echo"Haveagoodnight!";
}
?>
</body>
</html>

OUTPUT:

Thehour(oftheserver)is01,andwillgivethefollowingmessage: Have a

good morning!

TheswitchStatement

• Theswitchstatementisusedtoperformdifferentactionsbasedon
different conditions.

Usetheswitchstatementtoselectoneofmanyblocksofcodetobeexecuted.

Syntax
switch (n) {
caselabel1:
codetobeexecutedifn=label1;
break;
caselabel2:
codetobeexecutedifn=label2;
break;
caselabel3:
codetobeexecutedifn=label3;
break;
...
default:
codetobeexecutedifnisdifferentfromall labels;
}

Thisishowitworks:Firstwe have a single expression n (mostoftena variable),that is


evaluatedonce.Thevalueof theexpressionisthen compared withthevaluesforeach case
in the structure. If there is a match, the block of code associated with that case is
executed.Usebreaktopreventthecodefromrunningintothenextcaseautomatically. The
default statement is used if no match is found.
Example

<html>
<body>
<?php
$favcolor = "red";
switch($favcolor){
case"red":
echo"Yourfavoritecolorisred!";
break;
case"blue":
echo"Yourfavoritecolorisblue!"; break;
case"green":
echo"Yourfavoritecolorisgreen!"; break;
default:
echo"Yourfavoritecolorisneitherred,blue,nor green!";
}
?>
</body>
</html>

OUTPUT:

Yourfavoritecolorisred!

PHPLoops

Oftenwhenyouwritecode,youwantthesameblockofcodetorunoverandoveragain in arow.
Insteadofaddingseveralalmostequalcode-linesinascript, we canuse loops to perform a
task like this.

InPHP,wehavethefollowinglooping statements:

• while-loopsthroughablockofcodeaslongasthespecifiedconditionistrue
• do...while-loopsthroughablockofcodeonce,andthenrepeatstheloopas long as
the specified condition is true
• for-loopsthroughablockof codeaspecifiednumberoftimes
• foreach-loopsthrougha blockof codeforeachelementinanarray
ThePHPwhileLoop

• Thewhileloopexecutesablockofcodeaslongasthespecified conditionis true.

Syntax

while(conditionistrue){
codetobe executed;
}

The example below first sets a variable $x to 1 ($x = 1). Then, the while loop will
continue to run as long as $x is less than, or equal to 5 ($x <= 5). $x will increase by 1
each time the loop runs ($x++):

Example

<html>
<body>
<?php
$x= 1;
while($x<=5){
echo"Thenumberis:$x
<br>"; $x++;
}
?>
</body>
</html>

OUTPUT:

Thenumberis:1
Thenumberis:2
Thenumberis:3
Thenumberis:4
Thenumberis:5

ThePHPdo...whileLoop

Thedo...whileloopwillalwaysexecutetheblockofcodeonce,itwillthencheckthe condition,
and repeat the loop while the specified condition is true.

Syntax
do {
codetobeexecuted;} while
(condition is true);

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

Example

<html>
<body>
<?php
$x=1;
do {
echo"Thenumberis:$x<br>";
$x++;
}while($x<=
5); ?>
</body>
</html>

OUTPUT:

Thenumberis:1
Thenumberis:2
Thenumberis:3
Thenumberis:4
Thenumberis:5

Notice that in a do whileloop the condition is tested AFTER executing the statements
within the loop. This means that the do whileloop would execute its statements at least
once, even if the condition is false the first time.

Theexamplebelowsetsthe $xvariableto6,thenitrunstheloop, andthenthe condition is


checked:

Example

<html>
<body>
<?php
$x= 6;
do{
echo"Thenumberis:$x<br>";
$x++;
}while($x<=
5); ?>
</body>
</html>

OUTPUT:

Thenumberis:6

forLoops

• PHPforloopsexecuteablockof codeaspecifiednumberoftimes.

ThePHPforLoop

• Theforloopisusedwhenyouknowinadvancehowmanytimesthescript should
run.

Syntax
for(initcounter;testcounter;incrementcounter){
codetobe executed;
}

Parameters:

• initcounter:Initializetheloopcountervalue
• testcounter:Evaluatedforeachloopiteration.IfitevaluatestoTRUE,the loop
continues. If it evaluates to FALSE, the loop ends.
• incrementcounter:Increasestheloopcountervalue

The example below displays the numbers from 0 to 10:

Example

<html>
<body>
<?php
for ($x = 0; $x <= 10; $x++) {
echo"Thenumberis:$x<br>";
}
?>
</body>
</html>

OUTPUT:

The number is: 0


The number is: 1
The number is: 2
The number is: 3
The number is: 4
The number is: 5
The number is: 6
The number is: 7
The number is: 8
The number is: 9
Thenumberis:10

ThePHPforeachLoop

• Theforeachloopworksonlyonarrays,andisused toloopthrougheach
key/value pair in an array.

Syntax

foreach($arrayas$value)

{
codetobe executed;
}

• Foreveryloopiteration,thevalueofthecurrentarrayelementisassignedto
$valueandthearraypointerismovedbyone,untilitreachesthelastarray element.

• Thefollowingexampledemonstratesaloop thatwilloutputthevaluesofthe given


array ($colors):
Example

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

foreach($colorsas $value)
{echo"$value<br>";
}
?>
</body>
</html>

OUTPUT:

red
green
blue
yellow

WorkingwithArrays

PHP Indexed Arrays

• Therearetwowaystocreateindexedarrays:
• Theindexcanbeassignedautomatically(indexalwaysstartsat0),likethis:
• $cars=array("Volvo","BMW","Toyota");
• ortheindexcanbeassignedmanually:
• $cars[0]="Volvo";
$cars[1]="BMW";
$cars[2]="Toyota";
• Thefollowingexamplecreatesanindexedarraynamed$cars,assigns
three elements to it, and then prints a text containing the arrayvalues:

Example

<html>
<body>
<?php
$cars=array("Volvo","BMW","Toyota");
echo"Ilike".$cars[0]. ",".$cars[1] ." and".$cars[2].".";
?>
</body>
</html>
OUTPUT:

IlikeVolvo,BMWandToyota.
GetTheLengthofanArray-Thecount()Function

Thecount()functionisusedtoreturnthelength(thenumberofelements)ofanarray:
Example

<html>
<body>
<?php
$cars=array("Volvo","BMW","Toyota"); echo
count($cars);
?>
</body>
</html>

OUTPUT:

3
LoopThroughanIndexedArray

Toloopthroughandprintallthevaluesofanindexedarray,youcouldusea forloop, like this:

Example

<html>
<body>
<?php
$cars=array("Volvo","BMW","Toyota");
$arrlength=count($cars);

for($x=0;$x<$arrlength;$x++){ echo
$cars[$x];
echo"<br>";
}
?>
</body>
</html>

OUTPUT:

Volvo
BMW
Toyota
PHPAssociativeArrays

• Associativearraysarearraysthatusenamedkeysthatyouassigntothem.
• Therearetwowaystocreateanassociativearray:

$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");

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

• Thenamedkeyscanthenbeusedinascript:

Example

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

OUTPUT:

Peteris35yearsold.
LoopThroughanAssociative Array

Toloopthroughandprintallthevaluesofanassociativearray,youcoulduseaforeach loop, like


this:
Example

<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
foreach($age as $x => $x_value) {
echo"Key=".$x.",Value=".$x_value; echo

"<br>";
}
?>
SortingArrays

Theelementsinanarraycanbesortedinalphabeticalornumericalorder, descending
or ascending.

• sort()-sortarraysinascendingorder
• rsort()-sortarraysindescending order
• asort()-sortassociativearraysinascendingorder,accordingtothevalue
• ksort()-sortassociativearraysinascendingorder,accordingtothekey
• arsort()-sortassociativearraysindescending order,accordingtothevalue
• krsort()-sortassociativearraysindescendingorder,accordingtothekey
SortArrayinAscendingOrder-sort()

Thefollowingexamplesortstheelementsofthe$carsarrayinascending alphabetical
order:

Example

<html>
<body>
<?php
$cars=array("Volvo","BMW","Toyota");
sort($cars);

$clength=count($cars);
for($x=0;$x<$clength;$x++){
echo $cars[$x];
echo"<br>";
}
?>
</body>
</html>

OUTPUT:
BMW
Toyota
Volvo

Thefollowingexamplesortstheelementsofthe $numbersarrayinascending numerical


order:

Example
<?php
$numbers=array(4,6,2,22,
11);sort($numbers);
?>
OUTPUT:

2
4
6
11
22
SortArray(AscendingOrder),AccordingtoValue -asort()

Thefollowingexamplesortsanassociativearrayin ascendingorder,accordingtothe value:


Example

<?php

$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");

asort($age);
?>
OUTPUT:

Key=Peter,Value=35
Key=Ben, Value=37
Key=Joe, Value=43
SortArray(AscendingOrder),AccordingtoKey-ksort()

Thefollowingexamplesortsanassociativearrayinascendingorder,accordingtothe key:

Example
<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
ksort($age);
?>
OUTPUT:

Key=Ben, Value=37
Key=Joe, Value=43
Key=Peter,Value=35
SortArray(DescendingOrder),AccordingtoValue-arsort()

Thefollowingexamplesortsanassociativearrayindescendingorder,accordingtothe value:

Example
<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
arsort($age);
?>
OUTPUT:

Key=Joe, Value=43
Key=Ben, Value=37
Key=Peter,Value=35
SortArray(DescendingOrder),AccordingtoKey-krsort()

Thefollowingexamplesortsanassociativearrayindescendingorder,accordingtothe key:

Example
<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
krsort($age);
?>
OUTPUT:

Key=Peter,Value=35
Key=Joe, Value=43
Key=Ben, Value=37

• Anarraystoresmultiplevaluesinonesinglevariable.
• Inthefollowingexample$carsisanarray.ThePHPvar_dump()functionreturns the
data type and value:

Example

<html>
<body>
<?php
$cars=array("Volvo","BMW","Toyota");
var_dump($cars);
?>
</body>
</html>

OUTPUT:

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

Functions

• TherealpowerofPHPcomesfromitsfunctions;ithasmorethan1000built-in
functions.

PHPUserDefinedFunctions

• Besidesthebuilt-inPHPfunctions,wecancreateourownfunctions.
• Afunctionisablockofstatementsthatcanbeusedrepeatedlyinaprogram.
• Afunctionwillnotexecuteimmediatelywhenapageloads.
• Afunctionwillbeexecutedbya calltothefunction.
CreateaUserDefinedFunctionin PHP

Auser-definedfunctiondeclarationstartswiththewordfunction:

Syntax
functionfunctionName(){
codetobe executed;
}

• FunctionnamesareNOTcase-sensitive.

In the example below, we create a function named "writeMsg()". The opening curly
brace ( { ) indicates the beginning of the function code and the closing curly brace ( } )
indicates the end of the function. The function outputs "Hello world!". To call the
function, just write its name:
Example
<html>
<body>
<?php
function writeMsg()
echo"Helloworld!";
}
writeMsg();
?>
</body>
</html>

OUTPUT:

Helloworld!

PHPFunction Arguments

• Information can be passed to functions through arguments. An argument is just


like a variable.
• Arguments are specified after the function name, inside the parentheses. Youcan
add as many arguments as you want, just separate them with acomma.
• The following example has a function with one argument ($fname). When the
familyName() function is called, we also pass along a name (e.g. Jani), and the
name is used inside the function, which outputs several different first names, but
an equal last name:

Example
<html>
<body>
<?php
function familyName($fname) {
echo"$fnameRefsnes.<br>";
}
familyName("Jani");
familyName("Hege");
familyName("Stale");
familyName("KaiJim");
familyName("Borge");
?>
</body>
</html>

OUTPUT:

JaniRefsnes.
HegeRefsnes.
StaleRefsnes.
Kai JimRefsnes.
BorgeRefsnes.

Thefollowingexamplehasafunctionwithtwo arguments($fnameand$year):

Example
<html>
<body>
<?php
functionfamilyName($fname,$year){
echo"$fnameRefsnes.Bornin$year<br>";
}
familyName("Hege","1975");
familyName("Stale","1978");
familyName("Kai
Jim","1983"); ?>
</body>
</html>

OUTPUT:

Hege Refsnes. Born in 1975


Stale Refsnes. Born in 1978
KaiJimRefsnes.Bornin1983
PHPDefaultArgumentValue

• The following example shows how to use a default parameter. If we call the
functionsetHeight()withoutargumentsittakesthedefaultvalueasargument:

Example
<html>
<body>
<?php
function setHeight($minheight = 50) {
echo"Theheightis:$minheight<br>";
}
setHeight(350);
setHeight();
setHeight(135);
setHeight(80);
?>
</body>
</html>
OUTPUT:

Theheightis:350
The height is : 50
Theheightis:135
The height is : 80

PHPFunctions-Returningvalues

• Toletafunctionreturnavalue,usethereturnstatement:

Example
<html>
<body>
<?php
functionsum($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);
?>
</body>
</html>OU

TPUT:5+1

0=15
7+13=20
2+4 =6

WorkingwithFiles

•Filehandlingisanimportantpartofanywebapplication.Youoftenneedtoopen and
process a file for different tasks.
PHPManipulatingFiles

PHPhasseveralfunctionsforcreating,reading,uploading,andeditingfiles.

Becarefulwhenmanipulatingfiles!

• Whenyouaremanipulatingfilesyoumustbeverycareful.
• You can do a lot of damage if you do something wrong. Common errors are:
editing the wrong file, filling a hard-drive with garbage data, and deleting the
content of a file by accident.

PHPreadfile()Function

• Thereadfile()functionreadsafileandwritesittotheoutputbuffer.
• Assumewehaveatextfilecalled"webdictionary.txt",storedontheserver,that looks
like this:

AJAX=AsynchronousJavaScriptandXML
CSS = Cascading Style Sheets
HTML=HyperTextMarkupLanguage
PHP = PHP Hypertext Preprocessor
SQL = Structured Query Language
SVG = Scalable Vector Graphics
XML=EXtensibleMarkupLanguage

• ThePHPcodetoreadthefileandwriteittotheoutputbufferisasfollows(the readfile()
function returns the number of bytes read on success):

Example

<html>
<body>
<?php
echo readfile("webdictionary.txt");
?>
</body>
</html>
OUTPUT:

AJAX = Asynchronous JavaScript and XML CSS = Cascading Style Sheets HTML =
Hyper Text Markup Language PHP = PHP Hypertext Preprocessor SQL = Structured
Query Language SVG = Scalable Vector Graphics XML = EXtensible Markup
Language236
• Thereadfile()functionisusefulif allyouwanttodoisopenupafileandreadits contents.

File Open/Read/Close
PHPOpenFile-fopen()

• Abettermethodtoopenfilesiswiththefopen()function.Thisfunctiongives you more


options than the readfile() function.

Wewillusethetextfile,"webdictionary.txt", duringthelessons: AJAX =

Asynchronous JavaScript and XML


CSS=CascadingStyleSheets
HTML=HyperTextMarkupLanguage
PHP = PHP Hypertext Preprocessor
SQL = Structured Query Language
SVG = Scalable Vector Graphics
XML=EXtensibleMarkupLanguage

The first parameter of fopen() contains the name of the file to be opened and thesecond
parameter specifies in which mode the file should be opened. The following example
also generates a message if the fopen() function is unable to open the specified file:

Example
<?php
$myfile=fopen("webdictionary.txt","r")ordie("Unabletoopenfile!"); echo
fread($myfile,filesize("webdictionary.txt"));
fclose($myfile);
?>
OUTPUT:

AJAX = Asynchronous JavaScript and XML CSS = Cascading Style Sheets HTML =
Hyper Text Markup Language PHP = PHP Hypertext Preprocessor SQL = Structured
QueryLanguageSVG=ScalableVectorGraphicsXML=EXtensibleMarkupLanguage
Thefilemaybeopenedinoneofthefollowing modes:

Modes Description

r Openafileforreadonly.Filepointerstartsatthebeginningofthefile

wOpenafileforwriteonly.Erasesthecontentsofthefileorcreatesanewfileif it doesn't exist.


File pointer starts at the beginning of the file

aOpenafileforwriteonly.Theexistingdatainfileispreserved.Filepointerstartsat the end of


the file. Creates a new file if the file doesn'texist

x Createsanewfileforwriteonly.ReturnsFALSEandanerroriffilealreadyexists
r+ Openafileforread/write.Filepointerstartsatthebeginningofthefile

w+ Openafileforread/write.Erasesthecontentsofthefileorcreatesanewfileifit
doesn'texist.Filepointerstartsatthebeginningofthe file

a+ Openafileforread/write.Theexistingdatainfileispreserved.Filepointerstarts
attheendof thefile.Createsanewfileif thefiledoesn'texist

x+ Createsanewfileforread/write.ReturnsFALSEandanerroriffile already
Exists

PHPReadFile -fread()

• Thefread()functionreadsfromanopen file.
• Thefirstparameterof fread()containsthenameofthefiletoreadfromandthe second
parameter specifies the maximum number of bytes to read.
• ThefollowingPHPcodereadsthe"webdictionary.txt"filetotheend:

fread($myfile,filesize("webdictionary.txt"));
PHPCloseFile-fclose()

• Thefclose()functionisusedtocloseanopenfile.
• It'sagoodprogrammingpracticetocloseallfilesafteryouhavefinishedwith them.
You don't want an open file running around on your server taking up
resources!
• Thefclose()requiresthenameofthefile(oravariablethatholdsthefilename) we
want to close:

<?php
$myfile=fopen("webdictionary.txt",
"r");//somecodetobeexecuted....
fclose($myfile);
?>
PHPReadSingleLine -fgets()

• Thefgets()functionisusedtoreadasinglelinefromafile.
• Theexamplebelowoutputsthefirstlineofthe"webdictionary.txt"file:

Example
<?php
$myfile=fopen("webdictionary.txt","r")ordie("Unabletoopenfile!"); echo
fgets($myfile);
fclose($myfile);
?>
OUTPUT:

AJAX=AsynchronousJavaScriptandXML

Afteracalltothefgets()function,thefilepointerhasmovedtothenextline.

PHPCheckEnd-Of-File-feof()

• Thefeof()functionchecksifthe"end-of-file" (EOF)hasbeenreached.
• Thefeof()functionisusefulforloopingthroughdataof unknownlength.
• Theexamplebelowreadsthe"webdictionary.txt"filelinebyline,until end-of-file is
reached:

Example
<?php
$myfile=fopen("webdictionary.txt","r")ordie("Unabletoopenfile!");
//Outputonelineuntilend-of-file
while(!feof($myfile)) {
echofgets($myfile). "<br>";
}
fclose($myfile);
?>
OUTPUT:

AJAX=AsynchronousJavaScriptandXML
CSS = Cascading Style Sheets
HTML=HyperTextMarkupLanguage
PHP = PHP Hypertext Preprocessor
SQL = Structured Query Language
SVG = Scalable Vector Graphics
XML=EXtensibleMarkupLanguage

PHPReadSingleCharacter -fgetc()

• Thefgetc()functionisusedtoreadasinglecharacterfromafile.
• Theexamplebelowreadsthe"webdictionary.txt"filecharacterbycharacter,until end-
of-file is reached:

Example
<?php
$myfile=fopen("webdictionary.txt","r")ordie("Unabletoopenfile!");
//Outputonecharacteruntilend-of-file
while(!feof($myfile)){
echofgetc($myfile);
}
fclose($myfile);
?>
OUTPUT:

AJAX=AsynchronousJavaScriptandXMLCSS=CascadingStyleSheetsHTML=Hyper Text
Markup Language PHP = PHP Hypertext Preprocessor SQL = Structured Query
Language SVG = Scalable Vector Graphics XML = EXtensible Markup Language

• Afteracalltothefgetc()function,thefilepointermovestothenextcharacter.

File Create/Write
PHPCreateFile -fopen()

• Thefopen()functionisalsousedtocreateafile.Maybealittleconfusing,butin PHP, a
file is created using the same function used to openfiles.
• Ifyouusefopen()onafilethatdoesnotexist,itwillcreateit,giventhatthefileis opened for
writing (w) or appending (a).
• Theexamplebelowcreatesanewfilecalled"testfile.txt".Thefilewillbecreated in the
same directory where the PHP code resides:

Example
$myfile=fopen("testfile.txt","w")

PHPFilePermissions

Ifyouarehavingerrorswhentryingtogetthiscodetorun,checkthatyouhave granted
your PHP file access to write information to the hard drive.

PHPWritetoFile- fwrite()

• Thefwrite()functionisusedtowritetoafile.
• Thefirstparameteroffwrite()containsthenameofthefiletowritetoandthe second
parameter is the string to be written.
• Theexamplebelowwritesacoupleofnamesintoanewfilecalled"newfile.txt":

Example
<?php
$myfile=fopen("newfile.txt","w")ordie("Unabletoopen file!");
$txt = "John Doe\n";
fwrite($myfile,$txt);
$txt = "Jane Doe\n";
fwrite($myfile, $txt);
fclose($myfile);
?>

Notice that wewrote to the file "newfile.txt" twice. Each timewewrote to the file wesent
the string $txt that first contained "John Doe" and second contained "Jane Doe". After
we finished writing, we closed the file using the fclose() function.

Ifweopenthe"newfile.txt"fileitwouldlooklike this:

JohnDoe
JaneDoe

PHPOverwriting

• Now that "newfile.txt" contains some data we can show what happens when we
open an existingfilefor writing. All the existingdata willbe ERASEDand westart
with an empty file.
• In the example below we open our existing file "newfile.txt", and write some new
data into it:

Example
<?php
$myfile=fopen("newfile.txt","w")ordie("Unabletoopen file!");
$txt = "Mickey Mouse\n";
fwrite($myfile,$txt);
$txt="MinnieMouse\n";
fwrite($myfile, $txt);
fclose($myfile);
?>

Ifwenowopenthe"newfile.txt" file,bothJohnandJanehavevanished,andonlythe data we


just wrote is present:

OUTPUT:

MickeyMouse
MinnieMouse

PHPftp_fput()Function

Example

• Openlocalfile,anduploadittoafileontheFTPserver:
<?php
//connectandlogintoFTPserver
$ftp_server="ftp.example.com";
$ftp_conn = ftp_connect($ftp_server) or die("Could not connect to
$ftp_server");$login=ftp_login($ftp_conn,$ftp_username,$ftp_userpass);

//openfilefor reading
$file="test.txt";
$fp=fopen($file,"r");

//uploadfile
if(ftp_fput($ftp_conn,"somefile.txt",$fp,FTP_ASCII))
{
echo"Successfullyuploaded$file.";
}
else
{
echo"Erroruploading$file.";
}

//closethisconnectionandfilehandler
ftp_close($ftp_conn);
fclose($fp);
?>

DefinitionandUsage

• Theftp_fput()functionuploadsfromanopenfileandsavesittoafileonthe FTP
server.

Syntax
ftp_fput(ftp_connection,remote_file,open_file,mode,startpos);

Parameter Description

ftp_connectionRequired.SpecifiestheFTPconnectionto use

remote_file Required.Specifiesthefilepathtouploadto
open_file Required.Specifiesanopenlocalfile.Readingstopsatend
offile

mode Required.Specifiesthetransfermode.Possiblevalues:
FTP_ASCIIorFTP_BINARY

startpos Optional.Specifiesthepositionintheremotefiletostart
uploadingto

WorkingwithDatabases PHP

MySQL Database

• WithPHP,youcanconnecttoandmanipulatedatabases.
• MySQListhemostpopulardatabasesystemusedwithPHP.

Whatis MySQL?

• MySQLisadatabasesystemusedontheweb
• MySQLisadatabasesystemthatrunsonaserver
• MySQLisidealforbothsmallandlargeapplications
• MySQL isveryfast,reliable,andeasytouse
• MySQLusesstandardSQL
• MySQL compilesonanumberofplatforms
• MySQLisfreetodownloadanduse
• MySQLisdeveloped,distributed,andsupportedbyOracleCorporation

ThedatainaMySQLdatabasearestoredintables.Atableisacollectionofrelated data, and it


consists of columns and rows.

Databasesareusefulforstoringinformationcategorically.Acompanymayhavea database
with the following tables:

• Employees
• Products
• Customers
• Orders

PHP+MySQLDatabaseSystem

• PHPcombinedwithMySQLarecross-platform(youcandevelopinWindowsand serve
on a Unix platform)
PHPConnecttoMySQL

PHP5andlatercanworkwithaMySQLdatabaseusing:

• MySQLiextension (the"i"standsforimproved)
• PDO(PHPDataObjects)

EarlierversionsofPHPusedtheMySQLextension.However,thisextension was
deprecated in 2012.

ShouldIUseMySQLi orPDO?

Ifyouneedashortanswer,itwouldbe"Whateveryoulike". Both

MySQLi and PDO have their advantages:

• PDOwillworkon12differentdatabasesystems,whereasMySQLiwillonlywork with
MySQL databases.
• So, if you have to switch your project to use another database, PDO makes the
process easy. You only have to change the connection string and a few queries.
With MySQLi, you will need to rewrite the entire code - queriesincluded.
• Bothareobject-oriented,butMySQLialsooffersaproceduralAPI.
• BothsupportPreparedStatements.PreparedStatementsprotectfromSQL
injection, and are very important for web application security.

MySQLExamplesinBothMySQLiandPDOSyntax

Inthis,andinthefollowingchapterswedemonstratethreewaysofworkingwith PHP
and MySQL:

• MySQLi(object-oriented)
• MySQLi(procedural)
• PDO

MySQLiInstallation

• ForLinuxandWindows:TheMySQLiextensionisautomaticallyinstalledin most
cases, when php5 mysql package is installed.
• Forinstallationdetails,goto:http://php.net/manual/en/mysqli.installation.php
• PDO Installation
• Forinstallationdetails,goto:http://php.net/manual/en/pdo.installation.php
OpenaConnectiontoMySQL

• BeforewecanaccessdataintheMySQLdatabase, weneedtobeable to
connect to the server:

Example(MySQLiObject-Oriented)

<?php
$servername="localhost";
$username="username";
$password="password";

//Create connection
$conn=newmysqli($servername,$username,$password);

//Check connection
if($conn->connect_error) {
die("Connectionfailed:".$conn->connect_error);
}
echo"Connected
successfully"; ?>

Example(MySQLiProcedural)

<?php
$servername="localhost";
$username="username";
$password="password";

//Create connection
$conn=mysqli_connect($servername,$username,$password);

//Checkconnection if
(!$conn) {
die("Connectionfailed:".mysqli_connect_error());
}
echo"Connected
successfully"; ?>

Example (PDO)
<?php
$servername="localhost";
$username="username";
$password="password";

try{
$conn=newPDO("mysql:host=$servername;dbname=myDB",
$username,$password);
//setthePDOerrormodetoexception$conn-
>setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);echo
"Connectedsuccessfully";
}
catch(PDOException$e)
{
echo"Connectionfailed:".$e->getMessage();
}
?>

NoticethatinthePDOexampleabovewehavealsospecifiedadatabase(myDB).PDO require
a valid database to connect to. If no database is specified, an exception is thrown.

Tip: AgreatbenefitofPDOisthatithasanexceptionclasstohandleanyproblemsthat may


occur in our database queries. If an exception is thrown within the try{ } block, the script
stops executing and flows directly to the first catch(){ } block.

ClosetheConnection

Theconnectionwillbeclosedautomaticallywhenthescriptends.Toclosethe connection
before, use the following:

Example(MySQLiObject-Oriented)

$conn->close();

Example(MySQLiProcedural)

mysqli_close($conn);

Example (PDO)

$conn= null;
PHPCreateaMySQLDatabase
• Adatabaseconsistsofoneormore tables.
• YouwillneedspecialCREATEprivilegestocreateortodeleteaMySQL
database.
• CreateaMySQLDatabaseUsingMySQLi
• TheCREATEDATABASEstatementisusedtocreateadatabaseinMySQL.
• Thefollowingexamplescreateadatabasenamed"myDB":

Example(MySQLiObject-oriented)

<?php
$servername="localhost";
$username="username";
$password="password";

//Create connection
$conn=newmysqli($servername,$username,
$password);//Checkconnection if
($conn->connect_error) {
die("Connectionfailed:".$conn->connect_error);
}

//Create database
$sql="CREATEDATABASEmyDB";
if($conn->query($sql)===TRUE){
echo"Databasecreated
successfully"; } else {
echo"Errorcreatingdatabase:".$conn->error;
}
$conn-
>close();?>

Note:Whenyou create anewdatabase, youmustonlyspecifythefirst threearguments to


the mysqli object (servername, username and password).

Tip: Ifyouhavetouseaspecificport,addanemptystringforthedatabase-name argument, like


this: new mysqli("localhost", "username", "password", "", port)

PHPCreateMySQLTable

• Adatabasetablehasitsownuniquenameandconsistsofcolumnsandrows.
• CreateaMySQL TableUsingMySQLi
• TheCREATETABLEstatementisusedtocreateatableinMySQL.
• We willcreateatablenamed"MyGuests",withfivecolumns:"id","firstname",
"lastname", "email" and "reg_date":

CREATETABLEMyGuests(
idINT(6)UNSIGNEDAUTO_INCREMENTPRIMARY
KEY, firstname VARCHAR(30) NOT NULL,
lastnameVARCHAR(30)NOT
NULL, email VARCHAR(50),
reg_dateTIMESTAMP
)

Notesonthetableabove:

• Thedatatypespecifieswhattypeofdata thecolumncanhold.Foracomplete
reference of all the available data types, go to our Data Typesreference.

Afterthedatatype,youcanspecifyotheroptionalattributesforeach column:

• NOTNULL-Eachrowmustcontainavalueforthatcolumn,null valuesare not


allowed
• DEFAULTvalue -Setadefaultvaluethatisaddedwhennoothervalue is
passed
• UNSIGNED-Usedfornumbertypes,limitsthestoreddatatopositive
numbers and zero
• AUTOINCREMENT -MySQLautomaticallyincreasesthevalueofthefieldby 1
each time a new record is added
• PRIMARYKEY-Usedtouniquelyidentifytherowsinatable.Thecolumn with
PRIMARY KEY setting is often an ID number, and is often used with
AUTO_INCREMENT

Eachtableshouldhaveaprimarykeycolumn(inthiscase:the"id"column).Its value
must be unique for each record in the table.

ThefollowingexamplesshowshowtocreatethetableinPHP:

Example(MySQLiObject-oriented)

<?php
$servername="localhost";
$username="username";
$password="password";
$dbname="myDB";
//Create connection
$conn=newmysqli($servername,$username,$password,
$dbname);//Checkconnection if
($conn->connect_error) {
die("Connectionfailed:".$conn->connect_error);
}

//sqltocreatetable
$sql="CREATETABLEMyGuests(
idINT(6)UNSIGNEDAUTO_INCREMENTPRIMARY
KEY, firstname VARCHAR(30) NOT NULL,
lastnameVARCHAR(30)NOT
NULL, email VARCHAR(50),
reg_dateTIMESTAMP
)";

if($conn->query($sql)===TRUE){ echo
"Table MyGuests created
successfully";}else{
echo"Errorcreatingtable:".$conn->error;
}

$conn-
>close();?>

PHPInsertDataIntoMySQL

InsertDataIntoMySQLUsing MySQLi

• Afteradatabaseandatablehavebeencreated, wecanstartaddingdatain them.

Herearesomesyntaxrulestofollow:

• TheSQLquerymustbequotedinPHP
• StringvaluesinsidetheSQLquerymustbequoted
• Numericvaluesmustnotbequoted
• ThewordNULLmustnotbequoted

TheINSERTINTOstatementisusedtoaddnewrecordstoaMySQLtable:
INSERTINTOtable_name(column1,column2,column3,...)
VALUES (value1, value2, value3,...)

Note:IfacolumnisAUTO_INCREMENT(likethe"id"column)orTIMESTAMP(likethe
"reg_date" column), it is no need to be specified in the SQL query; MySQL will
automatically add the value.

Thefollowingexamplesaddanewrecordtothe"MyGuests"table:

Example(MySQLiObject-oriented)

<?php
$servername="localhost";
$username="username";
$password="password";
$dbname="myDB";

//Createconnection
$conn=newmysqli($servername,$username,$password,
$dbname);//Checkconnection if
($conn->connect_error) {
die("Connectionfailed:".$conn->connect_error);
}

$sql="INSERTINTOMyGuests(firstname,lastname,email) VALUES
('John', 'Doe', 'john@example.com')";

if($conn->query($sql)===TRUE){ echo
"New record created
successfully";}else{
echo"Error:".$sql."<br>".$conn->error;
}
$conn-
>close();?>

Example:

StudentApplicationusingPHPandMysql

aa.html:

<!DOCTYPE HTML>
<html>

<head>

<title>Student
Table</title></head>

<body>

<div id="dept"><h3 align=center>Student table


entry</h3><formmethod="POST"action="connect.php">

SName <br><input type="text" name="sname"><br>

Reg.No <br><input type="text" name="regno"><br>

Mark1<br><input type="text" name="m1"><br>

Mark2<br><inputtype="text"name="m2"><br><input

type="submit" value="ok">

</form>

</div>

</body>

</html>

Conn.php:

<?php

$servername="localhost";

$username="root";

$password="";

$dbname="sample";

//Create connection

$conn=newmysqli($servername,$username,$password,$dbname);
//Check connection
if($conn->connect_error)

die("Connectionfailed:".$conn->connect_error);

echo "Connected
successfully";//connecttable

$sql="descstudent";if($conn-
>query($sql)==TRUE)

echo"<br>";

echo"connectedtothetable";

else

echo"error";

//Inserting the

contentsecho"<br>";

//insertionfromhtml

$sname=$_POST['sname'];

$regno=$_POST['regno'];

$m1=$_POST['m1'];

$m2=$_POST['m2'];

$sql11="insertintostudentvalues('$sname',$regno,$m1,$m2)";

if($conn->query($sql11)==TRUE)
{

echo"inserted";

else

{echo"error";}
echo "<br>";

$sql1="select*fromstudent";

$result=$conn->query($sql1); if

($result->num_rows > 0) {

//outputdataofeachrow

echo"<b>SnameRegnoM1M2</b><br>";
while($row = $result->fetch_assoc()) {

echo$row["sname"]."".$row["regno"]."".$row["m1"]."".$row
["m2"]."<br>";

}else {

echo"emptytable";

$conn-
>close();?>

OUTPUT:
UNIT-5

PERL

Introduction to Perl
Perl is a general-purpose, high level interpreted and dynamic programming
language. It was developed by Larry Wall, in 1987. There is no official Full form
of the Perl, but still, the most used expansion is “Practical Extraction and
Reporting Language“.

Perl supports both the procedural and Object-Oriented programming. Perl is a


lot similar to C syntactically and is easy for the users who have knowledge
of C, C++. Evolution of Perl: It all started when Larry Wall was working on a
task to generate the reports from a lot of text files which have cross-references.
Then he started to use awk for this task but soon he found that it is not
sufficient for this task. So instead of writing a utility for this task, he wrote a new
language i.e. Perl and also wrote the interpreter for it.

Why Perl?
Perl has many reasons for being popular and in demand. Few of the reasons
are mentioned below:
 Easy to start: Perl is a high-level language so it is closer to other popular
programming languages like C, C++ and thus, becomes easy to learn for
anyone.
 Text-Processing: As the acronym “Practical Extraction and Reporting
Language” suggest that Perl has the high text manipulation abilities by which
it can generate reports from different text files easily. Also, it can convert the
files into some another form.
 Contained best Features: Perl contains the features of different languages
like C, sed, awk, and sh etc. which makes the Perl more useful and
productive.
 System Administration: Due to having the different scripting languages
capabilities Perl make the task of system administration very easy. Instead
of becoming dependent on many languages, just use Perl to complete out
the whole task of system administration. In Spite of this Perl also used in
web programming, web automation, GUI programming etc.
 Web and Perl: Perl can be embedded into web servers to increase its
processing power and it has the DBI package, which makes web-database
integration very easy.
Beginning with Perl Programming:
 Finding a Interpreter: There are various online IDEs which can be used to
run Perl programs without installing.
 Windows: There are various IDEs to run Perl programs or
scripts: Padre, Eclipse with EPIC plugin etc.
Example: A simple program to print Welcome to GFG!
# Perl program to print Welcome to GFG!
#!/usr/bin/perl

# Below line will print "Welcome to GFG!"


print "Welcome to GFG!\n";
Output:
Welcome to GFG!
Comments: Comments are used for enhancing the readability of the code. The
interpreter will ignore the comment entries and does not execute them.
Comments can be of the single line or multiple lines.
 Single line Comment: Syntax:
# Single line comment
 Multi-line comment: Syntax:
= Multi line comments
Line start from = is interpreted as the
starting of multiline comment and =cut is
consider as the end of multiline comment
=cut
Advantages of Perl:
 Perl Provides supports for cross platform and it is compatible with mark-up
languages like HTML, XML etc.
 It is very efficient in text-manipulation i.e. Regular Expression. It also
provides the socket capability.
 It is free and a Open Source software which is licensed
under Artistic and GNU General Public License (GPL).
 It is an embeddable language that’s why it can embed in web servers and
database servers.
 It supports more than 25, 000 open source modules
on CPAN(Comprehensive Perl Archive Network) which provide many
powerful extensions to the standard library. For example, XML processing,
GUI(Graphical User Interface) and DI(Database Integration) etc.
 Flexibility: Perl is a flexible language that allows programmers to solve
problems using a variety of approaches, making it easy to write code quickly
and efficiently.
 Regular expressions: Perl has excellent support for regular expressions,
which makes it ideal for text processing and data manipulation tasks.
 Large library of modules: Perl has a vast library of modules that can be used
to extend its functionality, making it easy to add complex
 features to your programs without having to reinvent the wheel.
 Cross-platform support: Perl runs on a wide range of platforms, including
Windows, Linux, macOS, and more.
 Easy to learn: Perl has a relatively simple syntax and is easy to learn,
especially for programmers who are familiar with other scripting languages.
Disadvantages of Perl:
 Perl doesn’t supports portability due to CPAN modules.
 Programs runs slowly and program needs to be interpreted each time when
any changes are made.
 In Perl, the same result can be achieved in several different ways which
make the code untidy as well as unreadable.
 Usability factor is lower when compared to other languages.
 Complex syntax: Perl’s flexibility can also be a disadvantage, as it can lead
to code that is difficult to read and maintain, especially for developers who
are new to the language.
 Performance: Perl is an interpreted language, which means that it can be
slower than compiled languages like C or Java for large or computationally
intensive programs.
 Legacy code: Because Perl has been around for over 30 years, there is a lot
of legacy code written in earlier versions of the language that may not be
compatible with newer versions.
 Security: Perl has some security concerns, such as the possibility of code
injection attacks if the input data is not properly sanitized.
Applications:
 One of the major application of Perl language is to processing of text files
and analysis of the strings.
 Perl also used for CGI( Common Gateway Interface) scripts.
 Used in web development, GUI(Graphical User Interface) development.
 Perl’s text-handling capabilities is also used for generating SQL queries
Application Areas

Fundamentals of Perl
Variables
Variables are user-defined words that are used to hold the values passed to the
program which will be used to evaluate the Code. Every Perl program contains
values on which the Code performs its operations. These values can’t be
manipulated or stored without the use of a Variable. A value can be processed
only if it is stored in a variable, by using the variable’s name.
A value is the data passed to the program to perform manipulation operations.
This data can be either numbers, strings, characters, lists, etc.
Example:
Values:
5
geeks
15

Variables:
$a = 5;
$b = "geeks";
$c = 15;
Operators
Operators are the main building block of any programming language. Operators
allow the programmer to perform different kinds of operations on operands.
These operators can be categorized based upon their different functionality:
 Arithmetic Operators
 Relational Operators
 Logical Operators
 Bitwise Operators
 Assignment Operators
 Ternary Operator

# Perl Program to illustrate the Operators

# Operands

$a = 10;

$b = 4;

$c = true;

$d = false;

# using arithmetic operators

print "Addition is: ", $a + $b, "\n";

print "Subtraction is: ", $a - $b, "\n" ;


# using Relational Operators

if ($a == $b)

print "Equal To Operator is True\n";

else

print "Equal To Operator is False\n";

# using Logical Operator 'AND'

$result = $a && $b;

print "AND Operator: ", $result, "\n";

# using Bitwise AND Operator

$result = $a & $b;

print "Bitwise AND: ", $result, "\n";

# using Assignment Operators


print "Addition Assignment Operator: ", $a += $b, "\n";

Output:

Addition is: 14
Subtraction is: 6
Equal To Operator is False
AND Operator: 4
Bitwise AND: 0
Addition Assignment Operator: 14
Number and its Types
A Number in Perl is a mathematical object used to count, measure, and perform
various mathematical operations. A notational symbol that represents a number
is termed a numeral. These numerals, in addition to their use in mathematical
operations, are also used for ordering(in the form of serial numbers).
Types of numbers:
 Integers
 Floating Numbers
 Hexadecimal Numbers
 Octal Numbers
 Binary Numbers

#!/usr/bin/perl

# Perl program to illustrate

# the use of numbers

# Integer

$a = 20;
# Floating Number

$b = 20.5647;

# Scientific value

$c = 123.5e-10;

# Hexadecimal Number

$d = 0xc;

# Octal Number

$e = 074;

# Binary Number

$f = 0b1010;

# Printing these values

print("Integer: ", $a, "\n");

print("Float Number: ", $b, "\n");

print("Scientific Number: ", $c, "\n");


print("Hex Number: ", $d, "\n");

print("Octal number: ", $e, "\n");

print("Binary Number: ", $f, "\n");

 Output:
 Integer: 20
 Float Number: 20.5647
 Scientific Number: 1.235e-08
 Hex Number: 12
 Octal number: 60
 Binary Number: 10
DataTypes
Data types specify the type of data that a valid Perl variable can hold. Perl is a
loosely typed language. There is no need to specify a type for the data while
using it in the Perl program. The Perl interpreter will choose the type based on
the context of the data itself.

Scalars
It is a single unit of data which can be an integer number, floating-point, a
character, a string, a paragraph, or an entire web page.
Example:
# Perl program to demonstrate

# scalars variables

# a string scalar

$name = "Alex";

# Integer Scalar

$rollno = 13;

# a floating point scalar

$percentage = 87.65;

# In hexadecimal form

$hexadec = 0xcd;

# Alphanumeric String

$alphanumeric = "gfg21";
# special character in string scalar

$specialstring = "^gfg";

# to display the result

print "Name = $name\n";

print "Roll number = $rollno\n";

print "Percentage = $percentage\n";

print "Hexadecimal Form = $hexadec\n";

print "String with alphanumeric values = $alphanumeric\n";

print "String with special characters = $specialstring\n";

Output:

Name = Alex
Roll number = 13
Percentage = 87.65
Hexadecimal Form = 205
String with alphanumeric values = gfg21
String with special characters = ^gfg
Arrays
An array is a variable that stores the value of the same data type in the form of
a list. To declare an array in Perl, we use ‘@’ sign in front of the variable name.
@number = (40, 55, 63, 17, 22, 68, 89, 97, 89)
It will create an array of integers that contains the values 40, 55, 63, 17, and
many more. To access a single element of an array, we use the ‘$’ sign.
$number[0]
It will produce the output as 40.
Array creation and accessing elements:

#!/usr/bin/perl

# Perl Program for array creation

# and accessing its elements

# Define an array

@arr1 = (1, 2, 3, 4, 5);

# using qw function

@arr2 = qw /This is a Perl Tutorial by GeeksforGeeks/;


# Accessing array elements

print "Elements of arr1 are:\n";

print "$arr1[0]\n";

print "$arr1[3]\n";

# Accessing array elements

# with negative index

print "\nElements of arr2 are:\n";

print "$arr2[-1]\n";

print "$arr2[-3]\n";

Output:

Elements of arr1 are:


1
4

Elements of arr2 are:


GeeksforGeeks
Tutorial
Strings
A string in Perl is a scalar variable and starts with a ($) sign and it can contain
alphabets, numbers, special characters. The string can consist of a single word,
a group of words, or a multi-line paragraph. The String is defined by the user
within a single quote (‘) or double quote (“).
#!/usr/bin/perl

# An array of integers from 1 to 10

@list = (1..10);

# Non-interpolated string

$strng1 = 'Using Single quotes: @list';

# Interpolated string

$strng2 = "Using Double-quotes: @list";

print("$strng1\n$strng2");

Output:

Using Single quotes: @list


Using Double-quotes: 1 2 3 4 5 6 7 8 9 10
Using Escape character in Strings:
Interpolation creates a problem for strings that contain symbols that might
become of no use after interpolation. For example, when an email address is to
be stored in a double-quoted string, then the ‘at’ (@) sign is automatically
interpolated and is taken to be the beginning of the name of an array and is
substituted by it. To overcome this situation, the escape character i.e. the
backslash(\) is used. The backslash is inserted just before the ‘@’ as shown
below:
#!/usr/bin/perl

# Assigning a variable with an email

# address using double-quotes

# String without an escape sequence

$email = "GeeksforGeeks0402@gmail.com";

# Printing the interpolated string

print("$email\n");

# Using '' to escape the

# interpolation of '@'

$email = "GeeksforGeeks0402\@gmail.com";

# Printing the interpolated string

print($email);

Output:

GeeksforGeeks0402.com
GeeksforGeeks0402@gmail.com
Escaping the escape character:
The backslash is the escape character and is used to make use of escape
sequences. When there is a need to insert the escape character in an
interpolated string, the same backslash is used, to escape the substitution of
escape character with ” (blank). This allows the use of escape characters in the
interpolated string.

#!/usr/bin/perl

# Using Two escape characters to avoid

# the substitution of escape(\) with blank

$string1 = "Using the escape(\\) character";

# Printing the Interpolated string

print($string1);

Output:

Using the escape(\) character

Hashes(Associative Arrays)
It is a set of key-value pairs. It is also termed as the Associative Arrays. To
declare a hash in Perl, we use the ‘%’ sign. To access the particular value, we
use the ‘$’ symbol which is followed by the key in braces.
Creating and Accessing Hash elements:

#!/usr/bin/perl

# Perl Program for Hash creation

# and accessing its elements

# Initializing Hash by

# directly assigning values

$Fruit{'Mango'} = 10;

$Fruit{'Apple'} = 20;

$Fruit{'Strawberry'} = 30;
# printing elements of Hash

print "Printing values of Hash:\n";

print "$Fruit{'Mango'}\n";

print "$Fruit{'Apple'}\n";

print "$Fruit{'Strawberry'}\n";

# Initializing Hash using '=>'

%Fruit2 = ('Mango' => 45, 'Apple' => 42, 'Strawberry' => 35);

# printing elements of Fruit2

print "\nPrinting values of Hash:\n";

print "$Fruit2{'Mango'}\n";

print "$Fruit2{'Apple'}\n";

print "$Fruit2{'Strawberry'}\n";

Output:

Printing values of Hash:


10
20
30
Printing values of Hash:
45
42
35
Control Flow
Decision Making
Decision Making in programming is similar to decision-making in real life. A
programming language uses control statements to control the flow of execution
of the program based on certain conditions. These are used to cause the flow of
execution to advance and branch based on changes to the state of a program.
Decision Making Statements in Perl :
 If
 If – else
 Nested – If
 if – elsif ladder
 Unless
 Unless – else
 Unless – elsif
 Example 1: To illustrate use of if and if-else

#!/usr/bin/perl

# Perl program to illustrate

# Decision-Making statements

$a = 10;

$b = 15;

# if condition to check
# for even number

if($a % 2 == 0 )

printf "Even Number";

# if-else condition to check

# for even number or odd number

if($b % 2 == 0 )

printf "\nEven Number";

else

printf "\nOdd Number";

 Output:
 Even Number
 Odd Number
Loops
Looping in programming languages is a feature that facilitates the execution of
a set of instructions or functions repeatedly while some condition evaluates to
true. Loops make the programmer’s task simpler. Perl provides the different
types of loop to handle the condition based situation in the program. The loops
in Perl are :
 for loop

#!/usr/bin/perl

# Perl program to illustrate

# the use of for Loop

# for loop

print("For Loop:\n");

for ($count = 1 ; $count <= 3 ; $count++)

print "GeeksForGeeks\n"

 Output:
 For Loop:
 GeeksForGeeks
 GeeksForGeeks
 GeeksForGeeks
 foreach loop

#!/usr/bin/perl
# Perl program to illustrate

# the use of foreach Loop

# Array

@data = ('GEEKS', 4, 'GEEKS');

# foreach loop

print("For-each Loop:\n");

foreach $word (@data)

print ("$word ");

 Output:
 For-each Loop:
 GEEKS 4 GEEKS
 while and do…. while loop

#!/usr/bin/perl

# Perl program to illustrate


# the use of foreach Loop

# while loop

$count = 3;

print("While Loop:\n");

while ($count >= 0)

$count = $count - 1;

print "GeeksForGeeks\n";

print("\ndo...while Loop:\n");

$a = 10;

# do..While loop

do {

print "$a ";


$a = $a - 1;

} while ($a > 0);

 Output:
 While Loop:
 GeeksForGeeks
 GeeksForGeeks
 GeeksForGeeks
 GeeksForGeeks

 do...while Loop:
 10 9 8 7 6 5 4 3 2 1
Subroutines
What are Subroutines?
A Perl function or subroutine is a group of statements that together perform a
specific task. In every programming language user want to reuse the code. So
the user puts the section of code in function or subroutine so that there will be
no need to write code again and again.
Example:

#!/usr/bin/perl

# Perl Program to demonstrate the

# subroutine declaration and calling

# defining subroutine
sub ask_user

print "Hello Geeks!\n";

# calling subroutine

# you can also use

# &ask_user();

ask_user();

Output:

Hello Geeks!
Multiple Subroutines
Multiple subroutines in Perl can be created by using the keyword ‘multi’. This
helps in the creation of multiple subroutines with the same name.
Example:
multi Func1($var){statement};
multi Func1($var1, $var2){statement1; statement2;}
Example:

#!/usr/bin/perl

# Program to print factorial of a number


# Factorial of 0

multi Factorial(0)

1; # returning 1

# Recursive Function

# to calculate Factorial

multi Factorial(Int $n where $n > 0)

$n * Factorial($n - 1); # Recursive Call

# Printing the result

# using Function Call

print Factorial(15);

Output:
3628800
To know more about Multiple Subroutines, please refer to Multiple Subroutines
in Perl
Modules and Packages
A module in Perl is a collection of related subroutines and variables that
perform a set of programming tasks. Perl Modules are reusable. Perl module is
a package defined in a file having the same name as that of the package and
having extension .pm. A Perl package is a collection of code which resides in its
own namespace.
To import a module, we use require or use functions. To access a function or a
variable from a module, :: is used.
Examples:

#!/usr/bin/perl

# Using the Package 'Calculator'

use Calculator;

print "Enter two numbers to multiply";

# Defining values to the variables

$a = 5;

$b = 10;

# Subroutine call

Calculator::multiplication($a, $b);
print "\nEnter two numbers to divide";

# Defining values to the variables

$a = 45;

$b = 5;

# Subroutine call

Calculator::division($a, $b);

File Handling
In Perl, a FileHandle associates a name to an external file, that can be used
until the end of the program or until the FileHandle is closed. In short, a
FileHandle is like a connection that can be used to modify the contents of an
external file and a name is given to the connection (the FileHandle) for faster
access and ease.
The three basic FileHandles in Perl are STDIN, STDOUT, and STDERR, which
represent Standard Input, Standard Output, and Standard Error devices
respectively.
Reading from and Writing to a File using FileHandle
Reading from a FileHandle can be done through the print function.

# Opening the file


open(fh, "GFG2.txt") or die "File '$filename' can't be opened";

# Reading First line from the file

$firstline = <fh>;

print "$firstline\n";

Output :

Basic Operations on Files


Multiple Operations can be performed on files using FileHandles. These are:
 Opening and Reading a File
 Writing to a File
 Appending to a File
 Reading a CSV File
File Test Operators
File Test Operators in Perl are the logical operators that return True or False
values. There are many operators in Perl that you can use to test various
different aspects of a file. For example, to check for the existence of a file -e
operator is used.
Following example uses the ‘-e’, existence operator to check if a file exists or
not:

#!/usr/bin/perl
# Using predefined modules

use warnings;

use strict;

# Providing path of file to a variable

my $filename = 'C:\Users\GeeksForGeeks\GFG.txt';

# Checking for the file existence

if(-e $filename)

# If File exists

print("File $filename exists\n");

else

{
# If File doesn't exists

print("File $filename does not exists\n");

Working with Excel Files


Excel files are the most commonly used office application to communicate with
computers. For creating excel files with Perl you can use padre IDE, we will
also use Excel::Writer::XLSX module.
Perl uses write() function to add content to the excel file.
Creating an Excel File:
Excel Files can be created using Perl command line but first we need to load
Excel::Writer::XLSX module.

#!/usr/bin/perl

use Excel::Writer::XLSX;

my $Excelbook = Excel::Writer::XLSX->new( 'GFG_Sample.xlsx' );

my $Excelsheet = $Excelbook->add_worksheet();

$Excelsheet->write( "A1", "Hello!" );


$Excelsheet->write( "A2", "GeeksForGeeks" );

$Excelsheet->write( "B1", "Next_Column" );

$Excelbook->close;

Output:

Reading from an Excel File:


Reading of an Excel File in Perl is done by using Spreadsheet::Read module in
a Perl script. This module exports a number of function that you either import or
use in your Perl code script. ReadData() function is used to read from an excel
file.
Example:

use 5.016;

use Spreadsheet::Read qw(ReadData);

my $book_data = ReadData (‘new_excel.xlsx');

say 'A2: ' . $book_data->[1]{A2};

Output:
A2: GeeksForGeeks

You might also like