You are on page 1of 8

PHP & MySQL Lab 1

What is PHP?
PHP is described in its official website http://www.php.net as:
PHP is a widely-used general-purpose scripting language that is especially suited for Web
development and can be embedded into HTM.
PHP is the recursive acronym for !PHP: Hyperte"t Preprocessor#.
$t is a server side scripting language. The PHP code is ran on the webserver and then the
output is returned to the user through a web browser.
PHP use has increased dramatically over the last % years. &o to http://www.php.net/usage.php to
find a survey on how popular PHP is. The main reasons for its popularity are:
$t is open-source and free'
(asy to use. $t has a very simple synta" unli)e other languages such as Perl or *. +ather
than writing lots of code to create a webpage, we create HTM documents and embed
simple PHP codes into them.
$t has multi-platform support. $t supports all ma-or operating systems. Moreover, the
synta" is consistent among different platforms. .ou can create PHP codes in Windows
and easily switch to /ni".
PHP supports many new technologies. $n particular, it supports My01.
The history of the PHP is 2uite interesting:
PHP succeeds an older product, named PHP/3$. PHP/3$ was created by +asmus erdorf
in 455%, initially as a simple set of Perl scripts for trac)ing accesses to his online resume.
He named this set of scripts 6Personal Home Page Tools6. 7s more functionality was
re2uired, +asmus wrote a much larger * implementation, which was able to communicate
with databases, and enabled users to develop simple dynamic Web applications. +asmus
chose to release the source code for PHP/3$ for everybody to see, so that anybody can use
it, as well as fi" bugs in it and improve the code.
PHP/3$, which stood for Personal Home Page / 3orms $nterpreter, included some of the
basic functionality of PHP as we )now it today. $t had Perl-li)e variables, automatic
interpretation of form variables and HTM embedded synta". The synta" itself was
similar to that of Perl, albeit much more limited, simple, and somewhat inconsistent.
8y 4559, PHP/3$ :.;, the second write-up of the * implementation, had a cult of several
thousand users around the world <estimated=, with appro"imately %;,;;; domains
reporting as having it installed, accounting for about 4> of the domains on the $nternet.
While there were several people contributing bits of code to this pro-ect, it was still at
large a one-man pro-ect.
PHP/3$ :.; was officially released only in ?ovember 4559, after spending most of its life
in beta releases. $t was shortly afterwards succeeded by the first alphas of PHP @.;.
3or more, go to http://us:.php.net/manual/en/history.phpAhistory.php .
/seful lin)s:
http://www.php.net The official PHP website. Bownloads, documentation, latest news
and release information and much more.
http://us@.php.net/tut.php 7n introductory tutorial.
http://www.php.net/docs.php Cnline PHP manuals.
http://www.planet-php.net/ atest news aggregated from PHP related weblogs.
http://www.hotscripts.com/PHP/ Many PHP resources including scripts you can
download.
http://www.-ustphu)it.com/php-tutorials.php 7 collection of PHP tutorials.
3C+ MC+( /0(3/ $?D0 &C TC http://www.php.net/lin)s.php .
We will use the PHP codes from !How to do (verything with PHP E My01# by
Fi)ram Wasvani, from Mc&raw Hill / Csbourne publications. .ou can buy the boo) from
7maGon. The boo) is also available at 8arnes E ?oble.
+ecall that PHP is a widely used general-purpose scripting language that is especially
suited for web development. PHP can be embedded into HTM documents to create
dynamically generated web pages 2uic)ly.
7ll PHP commands are enclosed within special start and end tags:
<?php
PHP code
?>
3or instance, if the PHP code is embedded into an HTM document, the PHP interpreter
reads and e"ecutes only the PHP code enclosed within the start and end tags.
To see how PHP wor)s with HTM, create the code below using notepad.

<html>
<head><basefont face= "Arial "></head>
<body>
<h2>Q: his creat!re can chan"e color to blend in #ith its
s!rro!ndin"s$ %hat is its name?</h2>
<?php
//print o!tp!t
echo "<h2><i>A: &hameleon </i></h2>"'
?>
</body>
</html>
7 PHP script consists of one or more statements, with each statement ending in a
semicolon <e": echo HIh:JIiJ7: *hameleon I/iJI/h:JKL =.
3or greater readability, you should add comments to your code. *omments can be
written after !//# <e": //print output=.
0ave this script as question.php and browse to it. Fiew the source code of the web page
you have created by clic)ing !0ource# in the !Fiew# tab in $nternet ("plorer. .ou will
see:
<html>
<head><basefont face="Arial"></head>
<body>
<h2>Q: his creat!re can chan"e color to blend in #ith its
s!rro!ndin"s$ %hat is its name?</h2>
<h2><i>A: &hameleon </i></h2>
</body>
</html>
When the code is e"ecuted, PHP converted the code inside the !IMphp# and !MJ# tags to
regular HTM code' (verything outside these tags is ignored by PHP and returned as is.
7 variable in PHP can be used to store both numeric and nonnumeric data.
(very variable has a name, which is preceded by a dollar <N= symbol.
Fariable names are case sensitive and they must begin with a letter or underscore
character.
We can replace the PHP code above with:
<?php
//define (ariable
)ans#er = *A: &hameleon*'
//print o!tp!t
+cho "<h2><i>)ans#er</i></h2>"'
?>
This will produce the same result as before.
To assign a value to a variable, use the e2uality <O= symbol <e": Nanswer O H7:
*hameleonKL =.
To use a variable value in your script, call the variable by its name. PHP will substitute
its value when the code is e"ecuted <e": (cho !Ih:JIiJNanswerI/iJI/h:J#L=.
.ou can add interactivity to your web site using 3C+M0. 7 form enables your users to
submit inputs to your web site. *reate the HTM document below to get user input <save
it as getinput.html=. Then we will manipulate this input using a PHP script.
<html>
<head></head>
<body>
<form action= "messa"e$php" method= "post">
+nter yo!r messa"e: <inp!t type= "te,t" name= "ms"" si-e= "./">
<inp!t type="s!bmit" (al!e="0end">
</form>
</body>
</html>
!action# attribute specifies the name of the script that will process the information
entered into the form. Here, the input entered into the form will be sent to message.php.
The value of the input entered is stored in the variable named msg.
?ow create the script that will process the input and save it as message.php:
<?php
// retrie(e form data in a (ariable
)inp!t = )1P203*ms"*4'
// print it
+cho "5o! said: <i>)inp!t</i>"'
?>
To access the value of a form variable, use its name inside NPPC0T <e":
NPPC0TQ*msg*R=.
?ow, run the getinput.html and enter some data into the form <!hello#= and submit it.
Message.php should read it and display it bac) to you <!.ou said: hello=.
There are four basic data types in PHP. PHP can automatically determine the variable
type by the conte"t in which it is being used.
Data Type Description Example
6oolean 0pecifies a tr!e or
false (al!e$
)a!th = tr!e'
7nte"er 7nte"ers li8e 9:;<
2///$
)a"e = 2;'
=loatin"9point =ractional n!mbers
s!ch as >2$; or
.$>?:.:>
)temp = @A'
0trin" 0eB!ence of
characters$ Cay be
enclosed in either
do!ble B!otes or
sin"le B!otes$
)name = D7smailE'
The data type of a variable can be retrieved by the function gettype($variable_name ).
$f a string variable is enclosed within double 2uotes, the variables are automatically
replaced by their values.
<?php
)identity = *Fames 6ond*'
// this #o!ld contain the strin" GCy name is Fames 6ondH
)sentence = "Cy name is )identity"'
// this #o!ld contain the strin" GCy name is )identityH
)sentence = *Cy name is )identity*'
?>
There are over 4% operators in PHP that can be used to perform operations on the
variables:
2perator %hat 7t Ioes
= Assi"nment
J Addition
9 0!btraction
K C!ltiplication
/ Ii(ision< ret!rns B!otient
L Ii(ision< ret!rns mod!l!s
$ 0trin" concatenation
= = +B!al to
= = = +B!al to and of the same type
M = = Not eB!al to or not of the same
type
<> Not eB!al to
<< <=< >< >= Oess than< Oess than or eB!al to
etc$
PP Oo"ical ANI
QQ Oo"ical 2R
,or Oo"ical S2R
M Oo"ical N2
PHP has its own set of rules about which operators have precedence over others
<Cperators on the same line have the same level of precedence=:
4. !'#
:. !S#, !/#, !>#
@. !T#, !-#, !.#
U. !I#, !IO#, !J#, !JO#
%. !O O#, !'O#, !O O O#, !'O O#
V. !EE#
9. !WW#
7 conditional statement enables you to test whether a specific condition is true or false,
and to perform different actions on the basis of the test result. We will use the if( )
statement to create conditional statements:
<?php
if Tconditional testU
V
do this'
W
else
V
do this'
W
?>
$f the conditional e"pression after !if# evaluates to true, all PHP code within the
following curly brac)ets is e"ecuted. $f not, the code coming after the !else# is e"ecuted.
The !else# part of the above code can be removed. $n that case, if the conditional
e"pression is false, the code within the curly braces is s)ipped and the lines following the
!if# construct are e"ecuted.
<?php
if T)temp >= >//U
V
echo *Xery hotM*'
W
else
V
echo *%ithin tolerable limits*'
W
?>
PHP also provides you with a way of handling multiple possibilities:
<?php
if T)co!ntry == *YZ*U
V
)capital = *Oondon*'
W
elseif T)co!ntry == *Y0*U
V
)capital = *%ashin"ton*'
W
elseif T)co!ntry == *=R*U
V
)capital = *Paris*'
W
else
V
)capital = *!n8no#n*'
W
?>

7 loop is a control structure that enables you to repeat the same set of commands over
and over again. The actual number of repetitions may be dependent on a number you
specify, or on the fulfillment of a certain condition.
The simplest loop in PHP is the while loop With this loop type, so long as the conditional
e"pression specified evaluates to true, the loop will continue to e"ecute. When the
condition is false, the loop will be bro)en and the statements following it will be
e"ecuted.
<?php
// define n!mber and limits for m!ltiplication tables
)n!m = >>'
)!pperOimit = >/'
)lo#erOimit = >'
// loop and m!ltiply to create table
#hile T)lo#erOimit <= )!pperOimitU
V
echo ")n!m , )lo#erOimit =" $ T)n!mK)lo#erOimitU'
)lo#erOimitJJ'
W
?>
This script uses a while loop to create a multiplication table for the given table. $t starts
with !44 " 4 O 44# and continues until !44 " 4; O 44;#.
!NlowerimitTTL# does the same -ob as !Nlowerimit O Nlowerimit T 4L#.
$f the loop condition evaluates as false on the first iteration of the loop, the loop will
never be e"ecuted. However, sometimes you might need to e"ecute a set of commands at
least once. +egardless of how the conditional e"pression evaluates. 3or such situations,
PHP offers the do-while loop. The construction of the do-while<= loop is such that the
statements within the loop are e"ecuted first, and the condition to be tested is chec)ed
after.
The structure of the do-while loop is as follows:
<?php
do
V
do this
W #hile Tcondition is tr!eU
?>
etKs now revise the previous PHP script so that it runs at least once, regardless of how
the conditional e"pression evaluates the first time.
<?php
// define n!mber and limits for m!ltiplication tables
)n!m = >>'
)!pperOimit = >/'
)lo#erOimit = >2'
// loop and m!ltiply to create table
do
V
echo ")n!m , )lo#erOimit =" $ T)n!mK)lo#erOimitU'
)lo#erOimitJJ'
W #hile T)lo#erOimit <= )!pperOimitU
?>
8oth while and do-while loops continue to iterate for so long as the specified conditional
e"pression remains true. 8ut there often arises a need to e"ecute a certain set of
statements a fi"ed number of times. We use the for<= loop for this purpose.
<?php
for Tinitiali-e co!nter' conditional test' !pdate co!nterU
V
do this
W
?>
The for loop uses a counter that is initialiGed to a numeric value, and )eeps trac) of the
number of times the loop is e"ecuted. 8efore each e"ecution of the loop, a conditional
statement is tested. $f it evaluates to true, the loop will e"ecute once more and the counter
will be incremented by 4 <or more=. $f it evaluates to false, the loop will be bro)en and
the lines following it will be e"ecuted instead.
To see how this loop can be used, create the following script, which lists all the numbers
between : and 4;;:
<?php
for T), = 2' ), <=>//' ),JJU
V
echo "),"'
W
?>

QUIZ (Due to the beginning of next class)
*reate a website that as)s a simple 2uestion and retrieves the viewerKs answer. Bisplay messages on the
screen depending on the answer:
$f the answer is correct, display !*ongratulations'#.
Ctherwise, display a message li)e !.our answer was ---------. The correct answer is --------.#
Please, save this webpage as !2uiG4.html# and H2uiG4.phpK and send the files to the &0$Ks email bo".

You might also like