php programming lecture 6: programming in php | sck3633 web programming |

97
PHP Programming Lecture 6: Programming in PHP | SCK3633 Web Programming |

Upload: micah-rhoades

Post on 16-Dec-2015

238 views

Category:

Documents


7 download

TRANSCRIPT

Page 1: PHP Programming Lecture 6: Programming in PHP | SCK3633 Web Programming |

PHP ProgrammingPHP Programming

Lecture 6: Programming in PHP | SCK3633 Web Programming |

Page 2: PHP Programming Lecture 6: Programming in PHP | SCK3633 Web Programming |

Today’s TopicsToday’s Topics

• Introduction• Fundamentals of PHP• Using Variables• Selection Statements• Repetition Statements

Lecture 6: Programming in PHP | SCK3633 Web Programming |

Page 3: PHP Programming Lecture 6: Programming in PHP | SCK3633 Web Programming |

IntroductionIntroduction

• PHP (PHP Hypertext Preprocessor) is a web scripting language.

• Specifically designed for web-based application development.

• It is a server-pages technology. PHP script is embedded into HTML.

Lecture 6: Programming in PHP | SCK3633 Web Programming |

Page 4: PHP Programming Lecture 6: Programming in PHP | SCK3633 Web Programming |

What is PHP?What is PHP?

• PHP stands for PHP: Hypertext Preprocessor

• PHP is a server-side scripting language, like ASP

• PHP scripts are executed on the server even though even though combined with an HTML code

• PHP supports many databases (MySQL, Informix, Oracle, Sybase, Solid, PostgreSQL, Generic ODBC, etc.)

• PHP is an open source software (OSS) • PHP is free to download and use

Lecture 6: Programming in PHP | SCK3633 Web Programming |

Page 5: PHP Programming Lecture 6: Programming in PHP | SCK3633 Web Programming |

What is a PHP File?What is a PHP File?

PHP files may contain text, HTML tags and scripts

PHP files are returned to the browser as plain HTML 

PHP files have a file extension of ".php", ".php3", or ".phtml"

Lecture 6: Programming in PHP | SCK3633 Web Programming |

Page 6: PHP Programming Lecture 6: Programming in PHP | SCK3633 Web Programming |

Web-based Architecture Using PHPWeb-based Architecture Using PHP

Lecture 6: Programming in PHP | SCK3633 Web Programming |

Page 7: PHP Programming Lecture 6: Programming in PHP | SCK3633 Web Programming |

How PHP Pages are Accessedand Interpreted

How PHP Pages are Accessedand Interpreted

Lecture 6: Programming in PHP | SCK3633 Web Programming |

Page 8: PHP Programming Lecture 6: Programming in PHP | SCK3633 Web Programming |

Where to Start?Where to Start?

Install an Apache server on a Windows or Linux machine

Install PHP on a Windows or Linux machine

Install MySQL on a Windows or Linux machine

Install PHP triad• All in one

• LAMP– Linux Apache MySQL PHP

Lecture 6: Programming in PHP | SCK3633 Web Programming |

Page 9: PHP Programming Lecture 6: Programming in PHP | SCK3633 Web Programming |

XAMPP for WindowsXAMPP for Windows• Download xampp-win32-1.7.4-VC6-

installer.exe from http://sourceforge.net

• Double-click the .exe file you downloaded.

• Choose a language from the menu, and then click OK

* In Vista you may see a message warning you that XAMPP may not work when installed in the C:\Program Files directory. Install in C:\XAMPP or D:\XAMPP

Lecture 6: Programming in PHP | SCK3633 Web Programming |

Page 10: PHP Programming Lecture 6: Programming in PHP | SCK3633 Web Programming |

• Click Install and finally, click the Finish button.

• Click Yes, to open the XAMPP Control PanelLecture 6: Programming in PHP | SCK3633 Web Programming |

Page 11: PHP Programming Lecture 6: Programming in PHP | SCK3633 Web Programming |

• Start Apache and MySQL by clicking on the "Start" buttons next to each item. If prompted by Windows Firewall, click the button labelled "Unblock"

Lecture 6: Programming in PHP | SCK3633 Web Programming |

Page 12: PHP Programming Lecture 6: Programming in PHP | SCK3633 Web Programming |

Open web browser. Go to http://localhost/. If you are directed to a page with the XAMPP logo, your installation is successful.

Lecture 6: Programming in PHP | SCK3633 Web Programming |

Page 13: PHP Programming Lecture 6: Programming in PHP | SCK3633 Web Programming |

Example 01Example 01

• Add files in D:\xampp\htdocs to run PHP scripts at http://localhost/ on any local web browser.

• Create a new folder tutorial in D:\xampp\htdocs.

• Write a test.php file and copy it in to D:\xampp\htdocs\tutorial

• To run the php file, browse https://localhost/tutorial/test.php

Lecture 6: Programming in PHP | SCK3633 Web Programming |

Page 14: PHP Programming Lecture 6: Programming in PHP | SCK3633 Web Programming |

Would Output The Following ...Would Output The Following ...

Lecture 6: Programming in PHP | SCK3633 Web Programming |

Page 15: PHP Programming Lecture 6: Programming in PHP | SCK3633 Web Programming |

Embedding PHP into HTMLEmbedding PHP into HTMLThere are different ways to embed PHP

scripts into HTML• <?php echo "Hello World"; ?>

• <? echo "Hello World"; ?>

• <script language="php“>

echo "Hello World";

</script>

• <% echo "Hello World"; %> (this format needs the PHP.ini option asp_tag to be turn on)

Lecture 6: Programming in PHP | SCK3633 Web Programming |

Page 16: PHP Programming Lecture 6: Programming in PHP | SCK3633 Web Programming |

Switching between HTML and PHP can be done at any time.

Example: print tag <BR> 100 times.

<?php for($i=0; $i<100; $i++) { ?> <BR><?php } ?>

Lecture 6: Programming in PHP | SCK3633 Web Programming |

Page 17: PHP Programming Lecture 6: Programming in PHP | SCK3633 Web Programming |

Including Files

Example:

<?php $message="Hello World"; include "hello.php";?>

<html> <head> <title></title>

</head> <body> <?php echo $message ?> </body> </html>

File: hello.phpOutput in the Web Browser:

Hello World

Lecture 6: Programming in PHP | SCK3633 Web Programming |

Page 18: PHP Programming Lecture 6: Programming in PHP | SCK3633 Web Programming |

Proper SyntaxProper Syntax

• If you have a syntax error then you have written one or more PHP statements that are grammatically incorrect in the PHP language.

The print statement syntax:

Lecture 6: Programming in PHP | SCK3633 Web Programming |

Page 19: PHP Programming Lecture 6: Programming in PHP | SCK3633 Web Programming |

Improper SyntaxImproper Syntax

Suppose you use the wrong syntax:1. <?php2. print ( “A simple initial script);3. ?>

Lecture 6: Programming in PHP | SCK3633 Web Programming |

Page 20: PHP Programming Lecture 6: Programming in PHP | SCK3633 Web Programming |

SyntaxSyntaxIdentifiers

• Variable names are case-sensitive.

• Function names (both built-in and user-defined functions) are NOT case-sensitive.

Comments/* C style comments */

// C++ style comments

# Bourne shell style comments

PHP Statements are terminated by semicolon.

Lecture 6: Programming in PHP | SCK3633 Web Programming |

Page 21: PHP Programming Lecture 6: Programming in PHP | SCK3633 Web Programming |

VariablesVariables• Preceded by a dollar sign ($).• There is no limit on the length of a variable

name.• Variable names in PHP are case-sensitive.

Valid Variable Names:

$counter$_COUNTER$user_name$user100

Invalid Variable Names:

$1counter$#counter

Example:

Lecture 6: Programming in PHP | SCK3633 Web Programming |

Page 22: PHP Programming Lecture 6: Programming in PHP | SCK3633 Web Programming |

Assigning New Values to VariablesAssigning New Values to Variables

• You can assign new values to variables:

$days = 3;$newdays = 100;$days = $newdays;

• At the end of these three lines, $days and

$newdays both have values of 100.Lecture 6: Programming in PHP | SCK3633 Web Programming |

Page 23: PHP Programming Lecture 6: Programming in PHP | SCK3633 Web Programming |

Variables ……Variables ……

• In PHP, we do not have to declare variables. • Variables are automatically declared by the PHP

intepreter, the first time a value is assigned to them.

• PHP variables are untyped; you can assign a value of any type to a variable.

Output ?

$var = “Hello World”;echo “$var\n”;$var = 1001;echo ‘<br />’echo “The number is $var\n”;

Example:

Lecture 6: Programming in PHP | SCK3633 Web Programming |

Page 24: PHP Programming Lecture 6: Programming in PHP | SCK3633 Web Programming |

Variables ……Variables ……

• In PHP, uninitialized variables have the value undef, which evaluates to different values, depending on its context.

• undef value for a numeric context is 0• undef value for a string context is an empty

string (“”)

Output ?$a=100;$str="World";$msg= $hello . $str; $c = $a + $b;

echo $msg, "\n";echo $c;

Example:

Lecture 6: Programming in PHP | SCK3633 Web Programming |

Page 25: PHP Programming Lecture 6: Programming in PHP | SCK3633 Web Programming |

Dynamic VariablesDynamic Variables

• Also known as variable variables.

• Syntax: $$var or ${$var}

• Meaning: obtain the value of the variable whose name is equal to the value of $var.

Lecture 6: Programming in PHP | SCK3633 Web Programming |

Page 26: PHP Programming Lecture 6: Programming in PHP | SCK3633 Web Programming |

Dynamic Variables …..Dynamic Variables …..

Output ?

$msg = "Hello World";$var = “msg";echo $$var;

Example 1:

How does it work?

$$var => $”msg” or $msg => “Hello World”;

Lecture 6: Programming in PHP | SCK3633 Web Programming |

Page 27: PHP Programming Lecture 6: Programming in PHP | SCK3633 Web Programming |

Dynamic Variables …..Dynamic Variables …..

$var ="hello";$$var = "World";

print $hello;

Output ?Example 2:

How does it work?

We created the variable $hello indirectly, where $$var means $”hello”, or just $hello.

The assignment statement $$var=“World” is equal to $hello=“World”

Lecture 6: Programming in PHP | SCK3633 Web Programming |

Page 28: PHP Programming Lecture 6: Programming in PHP | SCK3633 Web Programming |

ConstantsConstants

• Constant is a value that cannot be modified once it is declared.

• Constants are created using function define.

• Constant names by default are case-sensitive.

Output ?

define ("HELLO",“Hi World");define ("NUMBER", 5);

echo HELLO, "\n";echo ‘<br />’echo "The number is ", NUMBER;

Example:

Lecture 6: Programming in PHP | SCK3633 Web Programming |

Page 29: PHP Programming Lecture 6: Programming in PHP | SCK3633 Web Programming |

Data TypesData Types

PHP provides 4 primitive data types• Integer numbers

• Floating-point numbers

• String

• Boolean

PHP provides 2 compound data types• Array

• Object

Lecture 6: Programming in PHP | SCK3633 Web Programming |

Page 30: PHP Programming Lecture 6: Programming in PHP | SCK3633 Web Programming |

Using Arithmetic OperatorsUsing Arithmetic Operators

Lecture 6: Programming in PHP | SCK3633 Web Programming |

Page 31: PHP Programming Lecture 6: Programming in PHP | SCK3633 Web Programming |

WARNING: Using Variables withUndefined Values

WARNING: Using Variables withUndefined ValuesIf you accidentally use a variable that does not

have avalue assigned to it will have no value (called a

nullvalue).When a variable with a null value is used

in anexpression PHP, PHP may not generatean error and may complete the expression

evaluation. Forexample, the following PHP script will output x=

y=4.Example : undef_var2.php

Lecture 6: Programming in PHP | SCK3633 Web Programming |

Page 32: PHP Programming Lecture 6: Programming in PHP | SCK3633 Web Programming |

PHP Precedence RulesPHP Precedence Rules

PHP follows the precedence rules listed

below.• First it evaluates operators withinparentheses.• Next it evaluates multiplication anddivision operators.• Finally it evaluates addition andsubtraction operators.

Lecture 6: Programming in PHP | SCK3633 Web Programming |

Page 33: PHP Programming Lecture 6: Programming in PHP | SCK3633 Web Programming |

PHP Precedence RulesPHP Precedence Rules

For example, the first 2 statementsevaluate to 80 while the last to 180.

• $x = 100 - 10 * 2;• $y = 100 -(10 * 2);• $z = (100 -10) * 2;

Lecture 6: Programming in PHP | SCK3633 Web Programming |

Page 34: PHP Programming Lecture 6: Programming in PHP | SCK3633 Web Programming |

StringsStringsThree ways for creating a string in PHP

• Double quatation mark ("")

• Single quatation mark ('')

• Here document

Double-quoted strings are subject to variable substitution and escape sequence handling, while single quotes are not.

Lecture 6: Programming in PHP | SCK3633 Web Programming |

Page 35: PHP Programming Lecture 6: Programming in PHP | SCK3633 Web Programming |

Strings …..Strings …..

Example 1: double and single quatation

$a="World";echo "1. Hello \t$a\n";echo '2. Hi \t$a\n';echo "\n";

$b=' Peace';$c = $a.$b;echo "3. $a.$b = $c\n";echo "4. \$a.\$b = $c\n";

Output ?

Lecture 6: Programming in PHP | SCK3633 Web Programming |

Page 36: PHP Programming Lecture 6: Programming in PHP | SCK3633 Web Programming |

Strings …..Strings …..

Example 2: here document

$a ='World';$str = <<<EOT Hello $a This is a "multiline" string assigned using the 'heredoc' syntax.EOT;

echo $str;

Output ?

Lecture 6: Programming in PHP | SCK3633 Web Programming |

Page 37: PHP Programming Lecture 6: Programming in PHP | SCK3633 Web Programming |

Working with PHP String VariablesWorking with PHP String Variables

• Character strings are used in scripts to hold data such as customer names, addresses, product names, and descriptions.

• Consider the following example. $name="Christopher"; $preference="Milk Shake";

$name is assigned “Christopher” and the variable $preference is assigned “Milk Shake”.

Lecture 6: Programming in PHP | SCK3633 Web Programming |

Page 38: PHP Programming Lecture 6: Programming in PHP | SCK3633 Web Programming |

WARNING: Be Careful Not toMix Variable TypesWARNING: Be Careful Not toMix Variable Types

• Becareful not to mix string and numeric variable types.

• For example, you might expect the following statements to generate an error message, but they will not. Instead, they will output “y=1”.

<?php

$x ="banana";$sum = 1 + $x;print ("y=$sum");

?>

Lecture 6: Programming in PHP | SCK3633 Web Programming |

Page 39: PHP Programming Lecture 6: Programming in PHP | SCK3633 Web Programming |

Using the Concatenate OperatorUsing the Concatenate Operator

The concatenate operator combines two separate string variables into one.

For example, $fullname = $firstname . $lastname;

$fullname will receive the string values of $firstname and $lastname connected together.

For example,$firstname = "John";

$lastname = "Smith";$fullname = $firstname . $lastname;print ("Fullname=$fullname");

Lecture 6: Programming in PHP | SCK3633 Web Programming |

Page 40: PHP Programming Lecture 6: Programming in PHP | SCK3633 Web Programming |

TIP; An Easier Way to Concatenate Strings.TIP; An Easier Way to Concatenate Strings.

• You can also use double quotation marks to create

• concatenation directly,• For example,$Fullname2 = "$FirstName$LastName";

This statement has the same effect as$Fullname2 = $FirstName. “ ” . $LastName;

Lecture 6: Programming in PHP | SCK3633 Web Programming |

Page 41: PHP Programming Lecture 6: Programming in PHP | SCK3633 Web Programming |

The strlen() FunctionThe strlen() Function

• Most string functions require you to send them one or more arguments.

• Arguments are input values that functions use in the processing they do.

• Often functions return a value to the script based on the input arguments.

• For example

Lecture 6: Programming in PHP | SCK3633 Web Programming |

Page 42: PHP Programming Lecture 6: Programming in PHP | SCK3633 Web Programming |

The strlen() Function ExampleThe strlen() Function Example

<?php

$comments = "Good Job";$len = strlen($comments);print ("Length=$len");

?>

This PHP script would output “Length=8”.

Lecture 6: Programming in PHP | SCK3633 Web Programming |

Page 43: PHP Programming Lecture 6: Programming in PHP | SCK3633 Web Programming |

The trim() FunctionThe trim() Function

• This function removes any blank characters

from the beginning and end of a string.• For example, consider the following script:

<?php $in_name = " Joe Jackson "; $name = trim($in_name); print ("name=$name$name"); ?>

Lecture 6: Programming in PHP | SCK3633 Web Programming |

Page 44: PHP Programming Lecture 6: Programming in PHP | SCK3633 Web Programming |

The strtolower() andstrtoupper() FunctionsThe strtolower() andstrtoupper() Functions

• These functions return the input string in all uppercase or all lowercase letters,

respectively.• For example,

<?php$inquote = "Now Is The Time";$lower = strtolower($inquote);$upper = strtoupper($inquote);print ("upper=$upper lower=$lower");

?>

The above would output “upper=NOW IS THE TIME lower=now is the time”.

Lecture 6: Programming in PHP | SCK3633 Web Programming |

Page 45: PHP Programming Lecture 6: Programming in PHP | SCK3633 Web Programming |

The substr() FunctionThe substr() Function

Substr has the following general format:

Lecture 6: Programming in PHP | SCK3633 Web Programming |

Page 46: PHP Programming Lecture 6: Programming in PHP | SCK3633 Web Programming |

The substr() FunctionThe substr() Function

• The substr() function enumerates character positions starting with 0 (not 1),

• For example, in the string “Homer”, the “H” would be position 0, the “o” would be position 1, the “m” position 2, and so on.

• For example, the following would output “Month=12 Day=25”.

<?php

$date = "12/25/2002";$month = substr($date, 0, 2);$day = substr($date, 3, 2);print ("Month=$month Day=$day");

?>

Lecture 6: Programming in PHP | SCK3633 Web Programming |

Page 47: PHP Programming Lecture 6: Programming in PHP | SCK3633 Web Programming |

The substr() FunctionThe substr() Function• As another example, consider the following use of the

substr() function• It does not include the third argument (and thus returns a

substring from the starting position to the end of the search string).

<?php$date = "12/25/2002";$year = substr($date, 6);print ("Year=$year");

?>

The above script segment would output “Year=2002”.

Lecture 6: Programming in PHP | SCK3633 Web Programming |

Page 48: PHP Programming Lecture 6: Programming in PHP | SCK3633 Web Programming |

Creating HTML Input FormsCreating HTML Input Forms

• HTML Forms and not part of PHP language but important way to send data to scripts

Lecture 6: Programming in PHP | SCK3633 Web Programming |

Page 49: PHP Programming Lecture 6: Programming in PHP | SCK3633 Web Programming |

Starting And Ending HTML FormsStarting And Ending HTML Forms

• You can create HTML forms by using the HTML <form> and </form> tags.

Lecture 6: Programming in PHP | SCK3633 Web Programming |

Page 50: PHP Programming Lecture 6: Programming in PHP | SCK3633 Web Programming |

Creating Form ButtonsCreating Form Buttons• You can create submit and reset buttons

by placing the following within <form> & </form> tags.

The submit button will be labeled “Click ToSubmit”. The reset button will be labeled “Erase

and Restart”.

Lecture 6: Programming in PHP | SCK3633 Web Programming |

Page 51: PHP Programming Lecture 6: Programming in PHP | SCK3633 Web Programming |

A Full Example ...A Full Example ...The previous code can be executed athttp://webwizard.aw.com/~phppgm/C2/form1.html

Lecture 6: Programming in PHP | SCK3633 Web Programming |

Page 52: PHP Programming Lecture 6: Programming in PHP | SCK3633 Web Programming |

Creating Text Input BoxesCreating Text Input Boxes• Text input boxes create a form

element for receiving a single line of text input.

Will be 15 characters wide accepting a maximumof 20 characters. Will set a variable named fname

with value of whatever the end-user enter.

Lecture 6: Programming in PHP | SCK3633 Web Programming |

Page 53: PHP Programming Lecture 6: Programming in PHP | SCK3633 Web Programming |

Creating Password BoxesCreating Password Boxes

• Password boxes similar to text boxes except asterisks are displayed (instead of text input).

Will be 15 characters wide accepting a maximumof 20 characters. Will set a variable named pass1with value of whatever the end-user enter.

Lecture 6: Programming in PHP | SCK3633 Web Programming |

Page 54: PHP Programming Lecture 6: Programming in PHP | SCK3633 Web Programming |

Creating Text AreasCreating Text Areas

• The following creates a text area containing 4 rows and 50 columns.

The words “Your comments here” are the defaulttext. The variable name Comments will be available

to the form-handling script.

Lecture 6: Programming in PHP | SCK3633 Web Programming |

Page 55: PHP Programming Lecture 6: Programming in PHP | SCK3633 Web Programming |

Creating Radio ButtonsCreating Radio Buttons• Radio buttons are small circles that can

select by clicking them with a mouse. Only one within a group can be selected at once.

The name argument must be the same for all radiobuttons operating together. The value argument setsthe variable value that will be available to the form

processingscript.

Lecture 6: Programming in PHP | SCK3633 Web Programming |

Page 56: PHP Programming Lecture 6: Programming in PHP | SCK3633 Web Programming |

Creating Check BoxesCreating Check Boxes• Check boxes are small boxes on a form that create a check mark when the user clicks them.

The above create four independent check boxes;

that is, all four check box elements can beselected and each will set a value for a

differentvariable name.

Lecture 6: Programming in PHP | SCK3633 Web Programming |

Page 57: PHP Programming Lecture 6: Programming in PHP | SCK3633 Web Programming |

Creating Check BoxesCreating Check Boxes• Might want to create a set of check

boxes that use the same name argument.

The value received by the form-processing scriptwould be a comma-separated list of all items

checked.

Lecture 6: Programming in PHP | SCK3633 Web Programming |

Page 58: PHP Programming Lecture 6: Programming in PHP | SCK3633 Web Programming |

Creating Selection ListsCreating Selection Lists• Creates a box with a scrolling list of one or

more items that user can highlight and select.

This HTML code creates four options formatted in a scrolling list. Only two of these options are

displayed at the same time, and the user can select more than one option. Multiple selections are sent to the form-processing script as a comma separated list.

Lecture 6: Programming in PHP | SCK3633 Web Programming |

Page 59: PHP Programming Lecture 6: Programming in PHP | SCK3633 Web Programming |

Receiving Form Input into PHP ScriptsReceiving Form Input into PHP Scripts• To receive HTML form input into a PHP script:• Use a PHP var name that matches the variable defined in the form element’s name argument.

• For example, if form uses the following: <input type="radio" name="contact" value="Yes">

• Then form-handling PHP script could use a variable called $contact.

• If the user clicks the radio button, then $contact would = Yes

Lecture 6: Programming in PHP | SCK3633 Web Programming |

Page 60: PHP Programming Lecture 6: Programming in PHP | SCK3633 Web Programming |

Full ExampleFull Example• Suppose your HTML form uses the

following: Enter email address: <input type="text" size="16”

maxlength="20" name="email">

• Then can receive input as follows:1.<html>2.<head><title> Receiving Input </title> </head>3.<body>4.<font size=5>Thank You: Got Your Input.</font>5.<?php6. print ("<br>Your email address is $email");7.8. print ("<br> Contact preference is $contact");9. ?>

Lecture 6: Programming in PHP | SCK3633 Web Programming |

Page 61: PHP Programming Lecture 6: Programming in PHP | SCK3633 Web Programming |

Full Example...Full Example...The previous code can be executed athttp://webwizard.aw.com/~phppgm/C2/Form4Radio.html

Lecture 6: Programming in PHP | SCK3633 Web Programming |

Page 62: PHP Programming Lecture 6: Programming in PHP | SCK3633 Web Programming |

Register_Globals?Register_Globals?

• Since PHP 4.2.1, the default PHP configuration is require a different mechanism to receive input for security reasons (than the one just shown).

• Technical details: it is a PHP configuration option to turn REGISTER_GLOBALS OFF (new default) or ON in the php.ini configuration file.

• If your site has REGISTER_GLOBALS OFF you must use a different mechanism to receive

HTML Form Variables.

Lecture 6: Programming in PHP | SCK3633 Web Programming |

Page 63: PHP Programming Lecture 6: Programming in PHP | SCK3633 Web Programming |

How can you tell ifRegister_Globals is OFF?How can you tell ifRegister_Globals is OFF?

• Enter the following PHP script and run it.

<?PHP phpinfo(); ?>

• Search through the output for• REGISTER_GLOBALS and see if it is

set to OFF or ON.• If it is off you must use the

following way to receive input data.

Lecture 6: Programming in PHP | SCK3633 Web Programming |

Page 64: PHP Programming Lecture 6: Programming in PHP | SCK3633 Web Programming |

Getting input data withRegister_Globals OFF?Getting input data withRegister_Globals OFF?

• To receive data with REGISTER_GOBALS OFF you use a special variable called $POST.

$name $_POST[“name”];

Enclose in squarebracket and then quotes

Name of HTML formvariable (note do not use $)

Special PHP Global variable. Technically itis an associative array (covered in chptr 5.)

PHP variable name that you want to receivethe HTML form input.Lecture 6: Programming in PHP | SCK3633 Web Programming |

Page 65: PHP Programming Lecture 6: Programming in PHP | SCK3633 Web Programming |

A Full Example ...A Full Example ... The previous code can be executed at

http://webwizard.aw.com/~phppgm/C2/Form4Radio_NG.html

Lecture 6: Programming in PHP | SCK3633 Web Programming |

Page 66: PHP Programming Lecture 6: Programming in PHP | SCK3633 Web Programming |

Conditional/Selection Statements

Conditional/Selection Statements

Lecture 6: Programming in PHP | SCK3633 Web Programming |

Page 67: PHP Programming Lecture 6: Programming in PHP | SCK3633 Web Programming |

Using Conditional Test StatementsUsing Conditional Test Statements

Conditional statements provide a way for scripts to test for certain data values and then to react differently depending on the value found.

Same as C or C++Will examine

• PHP If...Else Statements

• Switch statement

Lecture 6: Programming in PHP | SCK3633 Web Programming |

Page 68: PHP Programming Lecture 6: Programming in PHP | SCK3633 Web Programming |

if Statementif Statement

Use an if statement to specify a test condition and a set of statements to run when a test condition is true.

Lecture 6: Programming in PHP | SCK3633 Web Programming |

if(expr){ statements } elseif(expr) { statements

} else { statements

}

if(expr): statementselseif(expr): statementselse: statementsendif;

Format 1: Format 2:

Page 69: PHP Programming Lecture 6: Programming in PHP | SCK3633 Web Programming |

Example 1:

What is the output if the $average is equal to 70?

if ($average > 69) {$Grade=“Pass”;print “Grade=$Grade ”;

}print “Your average was $average”;

Lecture 6: Programming in PHP | SCK3633 Web Programming |

Page 70: PHP Programming Lecture 6: Programming in PHP | SCK3633 Web Programming |

Test ExpressionsTest Expressions

Test expressions use test operators within their expressions. Test operators work much like the expression operators.

Test operators evaluate to true or false

Lecture 6: Programming in PHP | SCK3633 Web Programming |

Page 71: PHP Programming Lecture 6: Programming in PHP | SCK3633 Web Programming |

PHP Test OperatorsPHP Test Operators

Lecture 6: Programming in PHP | SCK3633 Web Programming |

Page 72: PHP Programming Lecture 6: Programming in PHP | SCK3633 Web Programming |

Comparing StringsComparing Strings

PHP represents strings using the ASCII code values.ASCII provides a standard, numerical way to represent

characters on a computer.

Every letter, number, and symbol is translated into a code

number. “A” is ASCII code 65, “B” is 66, “C” is 67, and etc. Lowercase “a” is ASCII code 97, “b” is 98, “c” is 99, and

etc. ASCII “A” is less than ASCII “a”, “B” is less than “b”, and

“c” is less than “d”. ASCII characters have ASCII code values lower than letters.

So ASCII character “1” is less than “a” or “A”

Lecture 6: Programming in PHP | SCK3633 Web Programming |

Page 73: PHP Programming Lecture 6: Programming in PHP | SCK3633 Web Programming |

Cont…Cont…

You can use == operator to check if one string is equal to another.

Also can use <, >, <=, and >= operators to compare string values using ASCII code values.

Lecture 6: Programming in PHP | SCK3633 Web Programming |

Page 74: PHP Programming Lecture 6: Programming in PHP | SCK3633 Web Programming |

Example 1:

Example 2:

$name1 = “George”;$name2 = “Martha”;

if ($name1 == $name2) {print (“$name1 is equal to $name2”);

} else {print (“$name1 is not equal to $name2”);

}

$name1 = “George”;$name2 = “Martha”;

if ($name1 < $name2) {print (“$name1 is less than $name2”);

} else {print (“$name1 is not less than $name2”);

}Lecture 6: Programming in PHP | SCK3633 Web Programming |

Page 75: PHP Programming Lecture 6: Programming in PHP | SCK3633 Web Programming |

elseif Clause elseif Clause

Use an elseif clause with an if statement to specify an additional test condition.

Format:

The above script checks the elseif test expression when the test condition for the if statement is false.

if (test expression) {one or more PHP statements

} elseif (test expression) {one or more PHP statements

}

Lecture 6: Programming in PHP | SCK3633 Web Programming |

Page 76: PHP Programming Lecture 6: Programming in PHP | SCK3633 Web Programming |

Cont…Cont…One or more elseif clause can be used with an if

statement.

Example:

if ($hour < 9) {print “Sorry, it is too early.”;

} elseif {$hour < 12) {print Good morning. The hour is $hour. ”);print “How can we help you?”;

} elseif ($hour < 13) {print “Sorry, we are out to lunch. ”;

} elseif ($hour < 17) {print “Good afternoon. The hour is $hour. ”;print “How can we help you?”;

} elseif ($hour <= 23) {print “Sorry, we have gone home already.”;

}

Lecture 6: Programming in PHP | SCK3633 Web Programming |

Page 77: PHP Programming Lecture 6: Programming in PHP | SCK3633 Web Programming |

else Clauseelse Clause

Use an else clause with if and possibly one or more elseif clauses specify set of statements to run when all the previous set test

conditions are false.

Format:

if (test expression) {one or more PHP statements

} else (test expression) {one or more PHP statements

}

Lecture 6: Programming in PHP | SCK3633 Web Programming |

Page 78: PHP Programming Lecture 6: Programming in PHP | SCK3633 Web Programming |

Cont…Cont…Example 1:

if ($count == 0) {print (“Time to reorder.”);$reorder=1;

} elseif ($count == 1) {$reorder=1;print (“Warning: we need to start reordering.”);

} elseif ($count > 1) {$reorder = 0;print (“We are OK for now.”);

} else {print (“Illegal value for count = $count”);

}

Lecture 6: Programming in PHP | SCK3633 Web Programming |

Page 79: PHP Programming Lecture 6: Programming in PHP | SCK3633 Web Programming |

Format 1:

switch(expr) { case expr1: statements break; case expr2: statements break; default: statements break;}

Format 2:switch(expr): case expr1: statements break; case expr2: statements break; default: statements break;endswitch;

Lecture 6: Programming in PHP | SCK3633 Web Programming |

switch Statement switch Statement

Use switch statement as another conditional test

Page 80: PHP Programming Lecture 6: Programming in PHP | SCK3633 Web Programming |

Example 1:

switch($rating) {case 1:

$rated = “Poor”;print “The rating was $rated”;break;

case 2:$rated = “Fair”;print “The rating was $rated”;break;

case 3:$rated = “Good”;print “The rating was $rated”;break;

default:print “Error: that rating does not exist”;

)

Cont…Cont…

Lecture 6: Programming in PHP | SCK3633 Web Programming |

Page 81: PHP Programming Lecture 6: Programming in PHP | SCK3633 Web Programming |

Lecture 6: Programming in PHP | SCK3633 Web Programming |

Page 82: PHP Programming Lecture 6: Programming in PHP | SCK3633 Web Programming |

PHP LoopingPHP Looping

Scripts can use loop statements to repeat sections of code.

Same as C or C++Advantages of loops include

• scripts can be more concise

• can write more flexible scripts

Activity 05

Lecture 6: Programming in PHP | SCK3633 Web Programming |

Page 83: PHP Programming Lecture 6: Programming in PHP | SCK3633 Web Programming |

Cont…Cont…

while - loops through a block of code if and as long as a specified condition is true

do...while - loops through a block of code once, and then repeats the loop as long as a special condition is true

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

foreach - loops through a block of code for each element in an array

Lecture 6: Programming in PHP | SCK3633 Web Programming |

Page 84: PHP Programming Lecture 6: Programming in PHP | SCK3633 Web Programming |

Repetition StatementsRepetition Statements

Format 1:

while(expr) { statements}

while statement

Format 2:

while(expr): statementsendwhile;

Lecture 6: Programming in PHP | SCK3633 Web Programming |

If initially false, then the statements within the loop body will never run.

A bad idea to create an Infinite Loop If the loop conditional test always true, then the loop will

never end. It will consume resources on the Web server and possibly

slow down other server activity.

Page 85: PHP Programming Lecture 6: Programming in PHP | SCK3633 Web Programming |

do { statements} while(expr);

do-while statement

Lecture 6: Programming in PHP | SCK3633 Web Programming |

Page 86: PHP Programming Lecture 6: Programming in PHP | SCK3633 Web Programming |

Format 1:

for(start_expr; cond_expr; iter_expr) { statements}

for statement

Format 2:

for(start_expr; cond_expr; iter_expr): statementsendfor;

Lecture 6: Programming in PHP | SCK3633 Web Programming |

Page 87: PHP Programming Lecture 6: Programming in PHP | SCK3633 Web Programming |

Format 1:

foreach(array_expression as $value) { statements}

foreach statement

Format 2:

foreach(array_expression as $value): statementsendforeach;

Format 3: associative array

foreach(hash_array as $key=>$value){ statements}

Lecture 6: Programming in PHP | SCK3633 Web Programming |

Page 88: PHP Programming Lecture 6: Programming in PHP | SCK3633 Web Programming |

Cont…Example 1:

$brands = array("National", "MEC", "Khind", "Toshiba");

foreach ($brands as $value) echo $value,"\n";

Output???

Lecture 6: Programming in PHP | SCK3633 Web Programming |

Page 89: PHP Programming Lecture 6: Programming in PHP | SCK3633 Web Programming |

Example 2:

$month["jan"] = "January";$month["feb"] = "February";$month["mar"] = "March";$month["apr"] = "April"; foreach ($month as $key => $value) echo "Key: $key, Value: $value \n";

Output???

Lecture 6: Programming in PHP | SCK3633 Web Programming |

Cont…

Page 90: PHP Programming Lecture 6: Programming in PHP | SCK3633 Web Programming |

break and continue statements

• break is used to stop a loop.• continue is used to skip the current iteration and go

to the next iteration in a loop.

Lecture 6: Programming in PHP | SCK3633 Web Programming |

Page 91: PHP Programming Lecture 6: Programming in PHP | SCK3633 Web Programming |

Cont…Example:

for ($i=1; $i<99; $i++){ if (($i%2)==0) continue; print ("$i is is an odd number\n"); if ($i>5) break;}

Output???

Lecture 6: Programming in PHP | SCK3633 Web Programming |

Page 92: PHP Programming Lecture 6: Programming in PHP | SCK3633 Web Programming |

Logical Test OperatorsLogical Test OperatorsPHP supports a set of logical test operators you can use

to create compound test expressions• used within an if statement or a while statement to specify more than one

test condition

Logical test operators:1. &&-the AND operator.

Example:

while($ctr < $max && $flag == 0)

2. ||-the OR operator.

Example:

if($ctr != $max || $flag == 0)

3. !-the NOT operator.

Example:

if(!=$flag == 0)

Lecture 6: Programming in PHP | SCK3633 Web Programming |

Page 93: PHP Programming Lecture 6: Programming in PHP | SCK3633 Web Programming |

PHP – Data transferPHP – Data transfer

Transferring data between client (web browser) to the server-side

Two method:

• Using form: POST method

• Through URL: GET method

Lecture 6: Programming in PHP | SCK3633 Web Programming |

Page 94: PHP Programming Lecture 6: Programming in PHP | SCK3633 Web Programming |

POST MethodPOST Method

· The body of the message is sent as a stream of data (HTML form data)

· Separated with the PHP URL in the FORM post URL

· Client send data to servlet using HTML form element

Lecture 6: Programming in PHP | SCK3633 Web Programming |

Page 95: PHP Programming Lecture 6: Programming in PHP | SCK3633 Web Programming |

Cont…Cont…

· Form tag<FORM METHOD=”post”

ACTION=”login.php” TARGET=“”>

· Fill the TARGET value if form result have to display in a different frame

· After coding all the form element (button, textfield, etc) FORM tag must be close using the equivalent end tag - </FORM>

· If you have multiple form in a single page every separate every form using the end tag

Lecture 6: Programming in PHP | SCK3633 Web Programming |

Page 96: PHP Programming Lecture 6: Programming in PHP | SCK3633 Web Programming |

GET methodGET method· The body of the message (the data) is appended to the PHP

URL,· http://myserver.com/hello.php

· Separated by a question mark · http://myserver.com/hello.php?

· Followed by name-value pair which separated by equals sign· If value consist of more than one word, separate it using plus

sign which the php will convert it to space character after parsing · name=john+doe

· Every consecutive name-value pair will be separated using ampersand sign (&)· name=john+doe&id=007

Lecture 6: Programming in PHP | SCK3633 Web Programming |

Page 97: PHP Programming Lecture 6: Programming in PHP | SCK3633 Web Programming |

SummarySummary

Use conditional statements to test for certain conditions and based on the results of the test, to run specific script statements.

Loops expand the types of programming problems that you can solve and allow you to solve some programming problems much more concisely

Use logical AND (&&), OR (||) and NOT (!) operators to carry out compound tests.

Use POST and GET method to transfer data between client and the server side.

Lecture 6: Programming in PHP | SCK3633 Web Programming |