27-06-2015databasestøttet web-publicering1 lektion 2: web-programmering med php introduktion til...
Post on 21-Dec-2015
213 views
TRANSCRIPT
04/18/23 Databasestøttet Web-publicering 1
Lektion 2: Web-programmering med PHP
• Introduktion til Web-programmering• Programmeringssproget PHP — det første script• Indlejring af kode og kommentarer• Variable og udregning med tal• Noget om tegn-strenge (character strings)• Betingede sætninger — if-statements• Løkker — while-loops• Brug af form variable• PHP scripts på Web-serveren
04/18/23 Databasestøttet Web-publicering 2
Introduktion til WEB-programmering
• Oversigt:• Klient (browser) request’er en side fra en Web-server• Web-serveren udfører prgrammet • Web-server-programmet tilgår (f.eks.) en database på
Webserver- maskinen• Resultatet af kørslen (HTML kode) sendes til klienten• HTTP er protokollen med hvilken data sendes mellem en klient
og en Web-server HTTP is the foundation for “the World Wide Web´´
• Many different languages can be used for writing Web server programs (i.e., script): ASP, Java, Perl, TCL, C, C++,
• PHP, Scheme, Lisp, Standard ML, Erlang, Haskell, C#, ...
04/18/23 Databasestøttet Web-publicering 3
Web Programming with PHPPHP is a programming language for Web programmingExample — hello.php:<html><head><title>Hello World</title></head>
<body><? echo "<p>Hi There, </p>";echo "<p>Greetings from a simple PHP script</p>"; ?>
</body>
</html>• PHP code is embedded in HTML code with the use of <? and ?>• The PHP command echo sends its argument (a character string "...") to the browser• PHP commands are ended with the character ;• When a browser requests the page hello.php on the Web server, the PHP code is
executed, which
results in HTML code, which again is sent to the browser:<html><head><title>Hello World</title></head><body><p>Hi There, </p><p>Greetings from a simple PHP script</p></body> </html>
04/18/23 Databasestøttet Web-publicering 4
Code Embeddings and Comments
• The following example illustrates three ways of embedding code in a PHP document — embed.php:
<html><head><title>Embeddings</title></head><body> <h2>Tree forms for embedding PHP in HTML</h2>
<ol><? echo "<li>The simple form</li>"; ?><?php echo "<li>A slightly longer
form</li>"; ?><script language="PHP">
// Comments in PHP code is not sent to the browser
echo "<li>The somewhat longer form</li>";
</script></ol>
</body></html>• Usually, we shall use the simple form <? ... ?>• Comments that extend over several lines can be written /* ... */
04/18/23 Databasestøttet Web-publicering 5
Variables in PHPVariables are used for storing values during the execution of a PHP scriptValues can, for instance, be character strings and numbersNames of variables are chosen freely by the programmer, although variable
names must start with the character $Example — homepage.php:<html><head><title>Home page</title></head>
<body><h2> <? $name = "Martin Feldman";
echo "Home page for ";echo $name;
?></h2><hr />This page is maintained by<? echo $name ?>
</body>
</html> /* Notice that a variable can be referred to more than once after it has been initialized with a value. */
04/18/23 Databasestøttet Web-publicering 6
Computation with NumbersThere are two types of numbers in PHP:1. Integers: 3, 9, 0, -1, ...2. Doubles (double precision): 3.0, 9.2, 0.13, -23.2, ...The usual number operations (e.g., +,-,*, and /) can be used in
computations. Example — dollars.php:<html><head><title>Dollars</title></head>
<body><h2>Dollars</h2>
<? $rate = 8.43;$kroner = 1000.0;$dollars = ($kroner - 20.0) / $rate;echo "For DKr. $kroner you receive \$
$dollars"; ?></body>
</html> // Notice:• It is possible to refer to a variable in a character string "..."• To insert a dollar-sign ($) in a character string, the character \ should
be placed before the dollar-sign
04/18/23 Databasestøttet Web-publicering 7
Arithmetic Operations and Evaluation Order (precedence)
• Operators with a high precedence bind stronger than operators with a low precedence, and are therefore evaluated first.
• The operators *, /, and % have higher precedence than + and -, thus operations with these operators are evaluated first.
• When operators have the same precedence (same degree of binding), evaluation goes from left to right.
Operator Betydning Eksempler:
* Multiplikation 1,5 * 60 24 * 60
/ Division 134.0 / 60 134 / 60
% Modulo (rest) — 134 % 60
+ Addition 1.1 + 60 14 + 60
- Subtraktion 1.1 - 60 134 - 60
04/18/23 Databasestøttet Web-publicering 8
Example: What is the type and value of the following expressions?
It is possible to construct arbitrarily complicated expressions, for instance:22 - 34 + 43 % 34 * 23 + 122 / 43.22 * 23 + 43 evaluates to 302.924
Without precedence rules, expressions can be ambiguous: Does 2+4*4 evaluate to 24 or 18?Because * has a higher precedence than +, 4*4 is evaluated first whereafter 2 is added.To evaluate the addition first, parentheses can be used: The expression (2+4)*4 evaluates to 24.
Because and = have the same precedence, 2*5/2 is evaluated from left to right, resulting in the value 5.
To evaluate the division first, parentheses can be used: The expression 2*(5/2) evaluates to the value 4.
Aritmetrisk udtryk Resultattype Resultat
1.5 * 60
150.0 / 60
150 / 60
134 % 60
1.1 + 60
1.1 – 60
04/18/23 Databasestøttet Web-publicering 9
More About Character Strings
Character strings in PHP can be expressed either by "..." or by ’...’.
In character strings on the form ’...’, variables cannot be referred to.
Example: If the variable $name contains the value Per, the two statementsecho "Your name is $name";
echo ’Your name is $name’;
result inYour name is Per
Your name is $name
Other special characters in character strings on the form "...":• \\ : backslash• \n : newline• \t : tabulator• \" : double quote
04/18/23 Databasestøttet Web-publicering 10
Appending of Character Strings
Character strings can be appended in PHP by using the character ‘.’
Example — strings.php:<html><head><title>Character Strings</title></head>
<body><? $firstname = "Martin";$lastname = "Elsman";$name = $firstname . " " . $lastname;echo "My name is $name";?>
</body></html>
04/18/23 Databasestøttet Web-publicering 11
Conditional Statements in PHPIf-statements are used for executing different code depending on some condition
Example — account.php:<html><head><title>Account</title></head>
<body><? $dollars = 8;if ( $dollars == 1 ) {echo "You have 1 Dollar on you account"; // if-branch} else {echo "You have $dollars Dollars on your account"; //
else-branch}?>
</body></html>A condition is either FALSE (the value 0) or TRUE (different from 0)If ($dollars == 1) is FALSE (value 0), the else-branch is executed. Otherwise the if-
branch is executed. Other condition operators = = : < less than <= less than or equal
> larger than >= larger than or equal != not equal
04/18/23 Databasestøttet Web-publicering 12
The If-statement in PHPThe general format:if ( condition1 ) {
statement1} elseif ( condition2 ) {
statement2} else {
statement3} //Meaning:1. compute the value of condition1.2. if different from 0 (i.e., TRUE) then execute statement1, otherwise3. compute the value of condition24. if different from 0 (i.e., TRUE) then execute statement2, otherwise5. execute statement3An arbitrary number of elseif-branches can be used.
It is possible to omit the closing else-branch.
04/18/23 Databasestøttet Web-publicering 13
Example: Body Mass Index — bmi.php<html><head><title>Body Mass Index</title></head>
<body> <h2>Body Mass Index</h2>
<? $weight = 70.0; $height = 180.0; echo "Weight: $weight kg. <br />Height:
$height cm.<br />"; $bmi = $weight / (($height/100.0) *
($height/100.0)); echo "Your BMI is $bmi<br />"; if ( $bmi < 20.0 ) {
echo "Your BMI is too low."; } elseif ( $bmi < 25.0 ) { echo "Your BMI is normal."; } else {
echo "Your BMI is too high."; }
?></body> </html>
04/18/23 Databasestøttet Web-publicering 14
Comparison Operators and their Precedence
• The arithmetic operators *, /, %, +, - bind stronger than the comparison operators <, <=, >, >=.
• The comparison operators <, <=, >, >= bind stronger than == and !=.
Operator Betydning Eksempel
< Mindre end $x < 60
=< Mindre end eller lig med $x <= 60
> Større end $x > 60
>= Større end eller lig med $x >= 60
== Lig med $x = = 60
!= Forskellig fra $x != 60
04/18/23 Databasestøttet Web-publicering 15
Example
Lad x ha’ værdien 2 og y ha’ værdien 4.
Husk: Tallet 1 betyder TRUE og = betyder FALSE.
Logisk Udtryk Resultat værdi
1 == 1
$x != $y
$x < 3 + $y
($x + $y > 3) == 0
0 != $x < 3
$x == $y == 0
04/18/23 Databasestøttet Web-publicering 16
Logical Operators and their Precedence
• The operator ! binds stronger than &&, which binds stronger than ||.• ! also binds stronger than the comparison operators and the arithmetic
operators.• && and || bind weaker than the comparison operators and the
arithmetic operators.• Evaluation goes from left to right.• If exp1 is FALSE in exp1 && exp2 then exp2 is not evaluated.• If exp1 is TRUE in exp1 || exp2 then exp2 is not evaluated.
Operator Betydning Eksempel
! Ikke-negation-NOT !($x == 60)
&& Og-konjunktion-AND 0 <= $x && $x < 60
|| Eller-disjunktion-OR $x < 0 || $x >= 60
04/18/23 Databasestøttet Web-publicering 17
Example: Hvad er resultatet af nedenstående logiske udtryk?
Lad x = 2 og y = 4.
Boolske udtryk Resultatværdi
! 0
! 1
! 1 == 0
! (1 == 0)
1 && 0
0 || 1
$x + $y > 3 && $x < $y
$x + $y == 3 || $x < 4
04/18/23 Databasestøttet Web-publicering 18
Løkker i PHP
Hvordan kan vi skrive teksten "I love Web programming" 20 gange ?
Dårlig løsning :echo "I love Web programming<br />"; ...18 gange...echo "I love Web programming<br />";
Bedre løsning: anvend en while-løkke til repetition — love.php:$counter = 20;while ( $counter >= 1 ) {
echo "I love Web programming<br />";$counter = $counter - 1;
}• Sætningen echo udføres 20 gange, med $counter = 20, 19, . . . , 1
• Det er vigtigt at indholdet af variablen $counter (i.e., et tal ) aftager (nedtælles) for hver udførelse af løkkens krop.
• Hvad sker der hvis variablen $counter ikke tælles ned?
04/18/23 Databasestøttet Web-publicering 19
Syntax for while-løkkerGenerelt format:
while ( condition ) {statement ;
}
Betydning:1. Evaluering af betingelsen condition2. Hvis resultatet er forskelligt fra 0 (i.e., TRUE), så udfør statement, og fortsæt
ved (1)
Således vil kroppen body i while-løkken (statement) udføres så længe betingelsen (condition) er TRUE
Ofte anvendt while-konstruktion — love.php:initialization ;while ( condition ) {statement ;increment ; // alternativ optælling}
04/18/23 Databasestøttet Web-publicering 20
Examples of while-loops — loops1.phpStandard loop, where $i takes the values __, __, __, __, __, __, __, __, __, __, __:
$i = 10;while ( $i >= 1 ) {
$i = $i - 1;}
echo "Loop Example 1: $i <br />";
Standard loop, where $i takes the values ___, ___, ___, ___, ___, ___:$i = 1;while ( $i <= 10 ) {
$i = $i + 2;}
echo "Loop Example 2: $i <br />";
Standard loop, where $i takes the values ___, ___, ___, ___, ___, ___, ___, ___:$i = 1;while ( $i <= 100 ) {
$i = $i * 2;}echo "Loop Example 3: $i <br />";
What is the value of $i after each loop?
04/18/23 Databasestøttet Web-publicering 21
Loop Exercises with while — loops2.php
Write a while-loop that outputs 64, 32, 16, 8, 4, 2, 1:$i = __ ;while ( __ >= __ ) {
echo "$i, ";$i = __ / __ ;
}Write a while-loop that outputs 2, 4, 6, 8, . . . , 100:
$i = __ ;while ( __ <= __ ) {
echo "$i, ";$i = $i + __ ;
}Write a while-loop that outputs 100, 110, 120, . . . , 200:
$i = __ ;while ( $i <= __ ) {
echo "$i, ";$i = $i + __ ;
}
04/18/23 Databasestøttet Web-publicering 22
Anvendelse af Form VariableDet er muligt for PHP at anvende data, fra brugere via HTML form. Eks.: The File exchange.html:<html><head><title>Exchange Bank</title></head>
<body> <h2>Exchange Bank</h2> <form action="exchange.php">Enter value in kroner:
<p><input name="kroner" /></p><p><input type="submit" value="Get Dollar Amount" /></p>
</form></body></html>The File exchange.php:<html><head><title>Exchange Bank</title></head>
<body> <h2>Exchange Bank</h2><? $rate = 8.43; $fee = 20.0;$dollars = ($kroner - $fee) / $rate;$dollars = number_format($dollars, 2, ",", ".");echo "For DKr. $kroner you receive \$$dollars"; ?><p><a href="exchange.html">New Computation</a>
</body></html>What problems does this exchange service have? Is the service robust?
04/18/23 Databasestøttet Web-publicering 23
PHP scripts på Web-serveren ved ITU
Når et PHP script (en fil med efternavn eller extension .php) gemmes i en brugers/studerendes mappe (folder)
H:\public_html\test.php
Vil scriptet blive udført, når en klient request’er filen relateret til brugerens hjemmeside:
http://www.itu.dk/people/user/test.php
Øvelser — Problem Set 2• Temperature Conversion• Multiplication Service• Apple Pie Service