web programming basics of php 1. objectives to learn how to store and access data in php variables...

38
Web Programming Basics of PHP 1

Upload: victoria-harris

Post on 24-Dec-2015

214 views

Category:

Documents


0 download

TRANSCRIPT

Web Programming

Basics of PHP

1

Objectives • To learn how to store and access data in PHP

variables• To understand how to create and manipulate

numeric and string variables• To review how to create HTML input forms• To learn how to pass data from HTML forms to PHP

scripts

PHP Variables• All variable names begin with $• No type declarations – dynamically typed

– don’t need to declare a variable before using it– don’t need to specify what type of data it will take

(system decides dynamically) • An unsigned variable has the value NULL• String literals are defined with either single

quotes (') or double quotes (")– $sum = 100.30;– print 'the sum is $sum'; the sum is $sum– print "the sum is $sum" ; the sum is 100.30

3

Assigning 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.

4

Selecting Variable Names• You can select just about any set of characters for a

variable name in PHP, but they must:– Use a dollar sign ($) as the first character– Use a letter or an underscore character (_) as the

second character– Cannot start with a numeric character

• Note:Try to select variable names that help describe their function. For example $counter is more descriptive than $c or $ctr.

5

Combining Variables and the print Statement

• That is, to print out the value of $x, write the following PHP statement:– print "$x";

• The following code will output "Brian is 6 years old".$age=6;print "Brian is $age years old.";

• What will the following output?: print 'Brian is $age years old.';

6

A Full Example (prog4.php)...

1. <?php2. $first_num = 12;3. $second_num = 356;4. $temp = $first_num;5. $first_num = $second_num;6. $second_num = $temp;7. print "first_num= $first_num <br />second_num=$second_num";8. ?>

Using Arithmetic Operators• For example

<?php$apples = 12;$oranges = 14;$total_fruit = $apples + $oranges;print "The total number of fruit is $total_fruit";

?>

• These PHP statements would output "The total number of fruit is 26."

8

Common PHP Numeric OperatorsTable 2.1 Common PHP Numeric Operators

Operator Effect Example Result

+ Addition $x = 2 + 2;

$x is assigned 4.

- Subtraction $y = 3; $y = $y – 1;

$y is assigned 2.

/ Division $y = 14 / 2;

$y is assigned 7.

* Multiplication $z = 4; $y = $z * 4;

$y is assigned 16.

% Modulus (Remainder)

$y = 14 % 3; $y is assigned 2.

9

A Full Example (prog5.php)<?php$columns = 20;$rows = 12;

$total_seats = $rows * $columns;$ticket_cost = 3.75;$total_revenue = $total_seats * $ticket_cost;$building_cost = 300;$profit = $total_revenue - $building_cost;

print "Total Number of Seats is $total_seats <br />";print "Each Ticket Costs $ticket_cost<br />";print "Total Revenue (Seats * Cost) is $total_revenue <br />";print "Building Cost is $building_cost<br />";print "Total Profit (Revenue - Building Cost) is $profit";?>

WARNING: Using Variables with Undefined Values

11

If you accidentally use a variable that does not have a value assigned to it will have no value (called a null value).

When a variable with a null value is used in an expression PHP, PHP may not generate an error and may complete the expression evaluation.

For example, the following PHP script will output x= y=4.

<?php$y = 3;$y=$y + $x + 1; // $x has a null valueprint "x=$x y=$y";?>

Writing Complex Expressions

• Operator precedence rules define the order in which the operators are evaluated. For example,

$x = 5 + 2 * 6;• The value of $x is either 42 or 17 depending

on order of evaluation. • Since multiplication evaluated before addition

operations, this expression evaluates to 17.

12

PHP Precedence Rules

• PHP follows the precedence rules listed below.– First it evaluates operators within

parentheses (brackets).– Next it evaluates multiplication and division

operators.– Finally it evaluates addition and subtraction

operators.

13

A Full Example (prog6.php)1. <?php2. $mark1 = 50;3. $mark2 = 100;4. $mark3 = 75;5. $average = ($mark1 + $mark2 + $mark3) / 3;6. print "The marks are $mark1 $mark2 and $mark3<br />";7. print "The average is $average";8. ?>

14

Example to try

<?

?>

15

Write a php script to calculate the volume of a box (length times height times width)• assign values to variables• calculate the volume• print out a statement with the variables plus the result (volume)

Working with PHP String Variables• Character strings are used to hold data such as names,

addresses and descriptions. • There is no practical limit to the length of a string in

PHP• Consider the following example.

– $name="Christopher";– $preference="Milk Shake";

• $name is assigned "Christopher" and the variable $preference is assigned "Milk Shake".

16

WARNING: Be Careful Not to Mix Variable Types

• Be careful not to mix string and numeric variable types.

• For example, you might expect the following program to generate an error message, but it does not. Instead, it will output "sum=1".

<?php$x ="banana";$sum = 1 + $x;print ("sum=$sum");?>

17

Using the Concatenate Operator• The concatenate operator (.) combines two separate

string variables into one. – $fullname = $firstname . $lastname;– $fullname will receive the string values of $firstname and

$lastname connected together.– <?php

$firstname = "John";

$lastname = "Smith";

$fullname = $firstname . " " . $lastname;

print "Fullname=$fullname" ;

?> Output: Fullname=John Smith

18

An Easier Way to Concatenate Strings

• You can also use double quotation marks to create concatenation directly (add strings together)

• For example

• $Fullname2 = "$FirstName $LastName";– This statement has the same effect as

• $Fullname2 = $FirstName . " " . $LastName;

19

The 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

20

$len = strlen($name);

Variable or value to work with

Name of functionReceives the number of

characters in $name

The strlen() Function Example

<?php $comments = "Good Job"; $len = strlen($comments); print "Length=$len"; ?> Output: Length=8

21

The 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 "in_name=$in_name$in_name<br />";

print "name=$name$name";

?>

Output: in_name=Joe JacksonJoe Jackson

name=Joe JacksonJoe Jackson22

The strtolower() and strtoupper() 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");?>Output: upper=NOW IS THE TIME lower=now is the time

23

The substr() Function

$part = substr( $name, 0, 5);

Assign theextracted sub-string into thisvariable.

Extract from thisstring variable.

Starting position tostart extraction from.

Number of charactersto extract. (If omitted it willcontinue to extract until the endof the string.)

24

• Substr has the following general format:

Substring example

<?php$name = "Ian Young";$firstname = substr($name, 0, 3);$secondname = substr($name, 4, 5);print "firstname is $firstname and secondname is $secondname";?>

25

I A N Y O U N G

0 1 2 3 4 5 6 7 8

The substr() Function

26

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<?php$date = "25/12/2002";$month = substr($date, 0, 2);$day = substr($date, 3, 2);print ("Day=$day Month=$month");?>

OUTPUT: Day=25 Month=12

The substr() Function

27

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 = "09/03/2006";$year = substr($date, 6); //start at position 7print ("Year=$year");?>

OUTPUT: Year=2006

Example To Try

• Write a php script to:– assign your full name (first & second name) to one variable– use substr($variable, start, end) and substr($variable, start)

to remove your firstname & surname from the string– count the number of characters in your first name and

surname using strlen($variable) – print your firstname and surname name with the number of

characters in each respectively

28

Other useful string functions

strcmp(string1, string2) - compares 2 variables & returns 0 if values are exactly equal >0 if string1 is greater than (alphabetically after) string2<0 of string 1 is less than (alphabetically before) string2strpos(string1, string2) - returns starting position if string2

occurs inside string1strrev(string) - reverses a stringltrim(string), rtrim(string) - removes extra spaces from

beginning(left hand side), end (right hand side) of string

29

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

Creating HTML Input Forms

Text BoxRadio Buttons

Check Box

Select Box

Text Area

Submit/Reset button

Getting input data

• To receive data use a special global variable called $_POST.

$name=$_POST["name"];

31

Enclose in squarebracket and then quotes

Name of HTML form variable (note do not use $)

Special PHP Global variable. Technically it is

an associative array (covered in chptr 5.)

PHP variable name that you want to receive the HTML form input.

Sendingform.html<html><head> <title> A Simple Form </title> </head><body><form action="receive1.php" method="post" ><h1> Click submit to start our initial PHP program.</h1><br> Email:<input type="text" size="16" maxlength="20" name="email"><p><input type="submit" value="Click To Submit"></p><p><input type="reset" value="Erase and Restart"></p></form></body> </html>

URL in browser http://localhost/~labuser/sendingform.html

Sendingform.html

33

Receive1.php Code

The HTML form uses the following:

• Email: <input type="text" size="16" maxlength="20" name="email">

Then Receive1.php can receive input as follows:

<html>

<head><title> Receiving Input </title> </head>

<body>

<font size=5>Thank You: Got Your Input.</font>

<?php

$email=$_POST["email"];

print "<br><br><font size=5>Your email address is $email</font>";

?>

</body></form>

These must match

Other global variables

• As well as $_POST there is $_GET & $_REQUEST• $_GET works similarly to $_POST except URL will be

displayed information sent in the browser's address bar (less secure) & limited to 100 characters

• $_REQUEST contains $_GET & $_POST (generalised request)

35

HTML Form Input Elements

• Textbox <input type="text" name="tbname" />• Radio Buttons <input type="radio" name="rbname"

value="val1"/>• Checkbox <input type="checkbox" name="cbname"

value="val1"/>• Selectbox <select name = "dbname" /> <option>option1</option> <option>option2</option></select>• Text area <textarea name="taname" cols="30" rows="5"> </textarea>

36

Summary• Variables are used to store and access data in

computer memory. You can associate a value with a variable, change that value, print it out, and perform many different operations on it.

• PHP supports both numeric and string variables. String variables use different methods for value manipulation (for example, concatenation) than numeric variables do.

37

Summary

• You can use HTML forms to pass data to PHP scripts. HTML form elements include text boxes, text areas, password boxes, check boxes, radio buttons, and selection lists.

• PHP scripts can receive form element input values by using a PHP variable name that matches the one specified in the form element’s name argument.

38