37
PHP: Further Skills By Trevor Adams

PHP: Further Skills By Trevor Adams. Topics covered Brief re-cap of core PHP characteristics Arrays Loops Code organisation Error handling Online resources

Embed Size (px)

Citation preview

Page 1: PHP: Further Skills By Trevor Adams. Topics covered Brief re-cap of core PHP characteristics Arrays Loops Code organisation Error handling Online resources

PHP: Further Skills

By Trevor Adams

Page 2: PHP: Further Skills By Trevor Adams. Topics covered Brief re-cap of core PHP characteristics Arrays Loops Code organisation Error handling Online resources

Topics covered

Brief re-cap of core PHP characteristics Arrays Loops Code organisation Error handling Online resources

Page 3: PHP: Further Skills By Trevor Adams. Topics covered Brief re-cap of core PHP characteristics Arrays Loops Code organisation Error handling Online resources

Brief Overview of Core PHP

Variables $ sign, weakly typed

Constants Conditional branching

If statement Switch statement Logical comparison

Interacting with browser $_POST $_GET HTML <form> elements

Page 4: PHP: Further Skills By Trevor Adams. Topics covered Brief re-cap of core PHP characteristics Arrays Loops Code organisation Error handling Online resources

Arrays - Simple collections

It is common to group related data Ordered set of related elements

Arrays in PHP are very simple Weakly typed just like $variables Accessed using [ ] brackets You encountered an array when posting a form $_POST is an array provided by PHP to present form data

Access array elements using a key Either numerical or text based key $_POST[“txtMsg”] $soldiers[0]

Page 5: PHP: Further Skills By Trevor Adams. Topics covered Brief re-cap of core PHP characteristics Arrays Loops Code organisation Error handling Online resources

Arrays - declare and use

Defining an array is similar to a variable Same rules apply to array variable names Can be declared empty or initialised

For example: $myarray = array(); $myarray[0] = “Trevor Adams”; echo $myarray[0]; Prints “Trevor Adams”;

Or: $myarray = (0 => “Trevor Adams”); echo $myarray[0]; Prints “Trevor Adams”;

Page 6: PHP: Further Skills By Trevor Adams. Topics covered Brief re-cap of core PHP characteristics Arrays Loops Code organisation Error handling Online resources

Arrays - Characteristics

Arrays can store any type of variable, including other arrays. E.g. $myarray = array(); $myarray[0] = array(); $myarray[0][0] = “Trevor Adams”; echo $myarray[0][0]; Prints “Trevor Adams”

There is no size limit Is limited by server capacity Be nice to your server

Page 7: PHP: Further Skills By Trevor Adams. Topics covered Brief re-cap of core PHP characteristics Arrays Loops Code organisation Error handling Online resources

Arrays - working with data

Arrays are collections of related data Sometimes necessary to process this data

Need a way of iterating through an array Arrays need repetitive operations

This means Loops! With out further a do…

* we shall come back to arrays soon

Page 8: PHP: Further Skills By Trevor Adams. Topics covered Brief re-cap of core PHP characteristics Arrays Loops Code organisation Error handling Online resources

Loops - iteration made easy

Many tasks involve iteration The repetition of a process Computer programs do the job well

PHP provides us with choices While Do For foreach

Each of them are useful in different ways

Page 9: PHP: Further Skills By Trevor Adams. Topics covered Brief re-cap of core PHP characteristics Arrays Loops Code organisation Error handling Online resources

Loops - While

While loops are the most simple loop type Similar in syntax to an IF statement

Code runs ‘while’ the test expression is true E.g. While($valid == true){

//execute commands //test the test expression

} BE SURE to make sure your code can exit the loop

At some point, valid must not equal true to break the loop Avoid infinite loops, they ruin everyone's day

Page 10: PHP: Further Skills By Trevor Adams. Topics covered Brief re-cap of core PHP characteristics Arrays Loops Code organisation Error handling Online resources

Loops - Do

Do loop is extremely similar to a while loop Major difference, text expression is at the end This loop will always execute at least once

E.g. Do {

//execute these statements at least once //another statement

} while($something == true); Again, make sure your loop can end!

Page 11: PHP: Further Skills By Trevor Adams. Topics covered Brief re-cap of core PHP characteristics Arrays Loops Code organisation Error handling Online resources

Loops - for

For loops are best when the number of iterations are known

Using pseudo code: for(set loop counter; test loop counter; adjust loop

counter) { // execute statements within braces

} Trivial example would be to print out a

multiplication table (up to 12)…

Page 12: PHP: Further Skills By Trevor Adams. Topics covered Brief re-cap of core PHP characteristics Arrays Loops Code organisation Error handling Online resources

Loops - for

$mulitple = 5; for($counter = 1; $counter<13; $counter++){

$answer = $multiple * $counter; echo “$counter * $multiple = “ . $answer .”<br />”;

} This code would result in output:

1 * 5 = 5 2 * 5 = 10 3 * 5 = 15 .. And so on

Ensure you do not erroneously adjust $counter during the loop

Page 13: PHP: Further Skills By Trevor Adams. Topics covered Brief re-cap of core PHP characteristics Arrays Loops Code organisation Error handling Online resources

Loops - foreach

We get back to arrays! The foreach loop is an extension of the for

loop Except you do not need to know the number of

elements It can move through an array for you

Extremely useful loop for traversing arrays

Page 14: PHP: Further Skills By Trevor Adams. Topics covered Brief re-cap of core PHP characteristics Arrays Loops Code organisation Error handling Online resources

Loops - foreach

The foreach loop is available in two formats Assume the following array:

$campus[“sot”] = “Stoke-on-Trent”; $campus[“sta”] = “Stafford”; $campus[“lic”] = “Lichfield”;

A foreach loop can be used to iterate the entire array

Page 15: PHP: Further Skills By Trevor Adams. Topics covered Brief re-cap of core PHP characteristics Arrays Loops Code organisation Error handling Online resources

Loops - foreach in use

First method allows us to get the values. E.g. foreach($campus as $campusname) {

echo $campusname . “<br />”; }

Would output: Stoke-on-Trent Stafford Lichfield

Page 16: PHP: Further Skills By Trevor Adams. Topics covered Brief re-cap of core PHP characteristics Arrays Loops Code organisation Error handling Online resources

Loops - foreach in use

The second method allows access to the key: foreach($campus as $key => $name) {

echo “$key - $name<br />”; }

Would produce output: sot - Stoke-on-Trent sta - Stafford lic - Lichfield

This loop is excellent at traversing arrays of elements of unknown quantity

Page 17: PHP: Further Skills By Trevor Adams. Topics covered Brief re-cap of core PHP characteristics Arrays Loops Code organisation Error handling Online resources

Arrays and Loops - overview

Arrays - collections of related data Act like variables Access sub-elements using square brackets [ ] Can index elements with numerical or textual keys

Loops - useful for repetitive processing while and do test a Boolean expression

($something == true) for loops require a counter foreach loops traverse arrays

Page 18: PHP: Further Skills By Trevor Adams. Topics covered Brief re-cap of core PHP characteristics Arrays Loops Code organisation Error handling Online resources

Code Organisation

All about being efficient and productive Skills you should possess as a programmer

Creating functions Calling functions Scope

Modular code Placing code in separate files Make commonly used code available

Page 19: PHP: Further Skills By Trevor Adams. Topics covered Brief re-cap of core PHP characteristics Arrays Loops Code organisation Error handling Online resources

Functions - defining and using

We create functions for a number of reasons Avoid repetition (E.g. frequently used

calculations) Easier to test small code fragments

Functions have a name, and optionally may take arguments

Functions may merely execute commands They might return a value Completely up to the programmer

Page 20: PHP: Further Skills By Trevor Adams. Topics covered Brief re-cap of core PHP characteristics Arrays Loops Code organisation Error handling Online resources

Functions - defining and using

You can declare a function anywhere inside PHP code blocks

A function is declared using the keyword ‘function’. E.g. function sum_numbers ($a, $b) {

return $a + $b; }

This function could then be used in PHP code. E.g. $num1 = 4; $num2 = 6; $myAnswer = sum_numbers($num1, $num2); echo $myAnswer; // would show 10

Page 21: PHP: Further Skills By Trevor Adams. Topics covered Brief re-cap of core PHP characteristics Arrays Loops Code organisation Error handling Online resources

Functions - defining and using

function sum_numbers ($a, $b) { return $a + $b;

} $a and $b in this function are arguments They exist inside the function braces only It is said they have local scope Values you pass to a function are not

affected outside of it

Page 22: PHP: Further Skills By Trevor Adams. Topics covered Brief re-cap of core PHP characteristics Arrays Loops Code organisation Error handling Online resources

Functions - defining and using

A function does not have to return a value Possible to use output text E.g. creating a HTML header and footer function function print_header($title) {

echo “<html><head><title>$title</title></head>”; echo “<body>”;

} Function print_footer() {

echo “</body></html>”; }

Page 23: PHP: Further Skills By Trevor Adams. Topics covered Brief re-cap of core PHP characteristics Arrays Loops Code organisation Error handling Online resources

Functions - defining and using

<?php print_header(“Sample page”); echo “<p>Hello World!</p>; print_footer();

?> Would produce:

<html><head><title>Sample page</title></head><body> <p>Hello World!</p> </body></html>

Page 24: PHP: Further Skills By Trevor Adams. Topics covered Brief re-cap of core PHP characteristics Arrays Loops Code organisation Error handling Online resources

Code - Include / Require

PHP files do not have to be web pages It is possible to have a PHP made completely of

functions If this page was to be called in a browser, it would be

completely blank Including other files within a PHP script is a common

form of modularisation Common with many server side scripting languages

Allows the programmer to place code required in many places into one location, available to all scripts.

Page 25: PHP: Further Skills By Trevor Adams. Topics covered Brief re-cap of core PHP characteristics Arrays Loops Code organisation Error handling Online resources

Code - Include / Require PHP uses the include function and the require function

to incorporate other files Place our print_header and print_footer in a file called

utils.php We create index.php - we can then use:

<?php include(“utils.php”); print_header(“My Homepage”); echo “<h1>Hello World!</h1>”; print_footer(); ?>

Require can be used instead of include Require causes a page error however, if the file to include cannot

be found

Page 26: PHP: Further Skills By Trevor Adams. Topics covered Brief re-cap of core PHP characteristics Arrays Loops Code organisation Error handling Online resources

Code Organisation - Overview

Functions allow you to separate your frequently used code Promotes good practice Code re-use Less typing!

Include files allow a programmer to create useful libraries of code Promotes further good practice Allows you to create global code

Page 27: PHP: Further Skills By Trevor Adams. Topics covered Brief re-cap of core PHP characteristics Arrays Loops Code organisation Error handling Online resources

Error Handling with PHP

We should now have enough basic programming knowledge to consider errors

Error handling is perhaps one of the main weak points of PHP

We shall be covering: Why we care Notices Syntax errors Program errors Logical errors How to handle and avoid errors

Page 28: PHP: Further Skills By Trevor Adams. Topics covered Brief re-cap of core PHP characteristics Arrays Loops Code organisation Error handling Online resources

Why do we care about errors?

Security - paramount to any web application Data comes from non-trusted sources (users!)

Web messages Standard programs have the ability to pipe error messages

in many ways (log, dialog etc.) PHP only has the option of outputting messages to the

browser It does so, you might have already seen messages in your

own code Nothing says amateur like rogue error messages in

a production application

Page 29: PHP: Further Skills By Trevor Adams. Topics covered Brief re-cap of core PHP characteristics Arrays Loops Code organisation Error handling Online resources

PHP Errors - Notices

A notice is not actually an error at all It merely serves as information to the

programmer <?php

echo "<h1>$message</h1>"; ?>

Produces: QuickTime™ and aTIFF (Uncompressed) decompressor

are needed to see this picture.

Page 30: PHP: Further Skills By Trevor Adams. Topics covered Brief re-cap of core PHP characteristics Arrays Loops Code organisation Error handling Online resources

PHP Errors - Notices

You know that @ suppresses the message A better technique is to test the variable first

Use the isset() function or the empty() function isset($varname) returns true if the variable has been given a

value empty($varname) returns true if it is null

<?php If(isset($message)) {

echo “<h1>$message</h1>”; } ?>

Testing the variable for a value removes the warning message from the script

Page 31: PHP: Further Skills By Trevor Adams. Topics covered Brief re-cap of core PHP characteristics Arrays Loops Code organisation Error handling Online resources

PHP Errors - Syntax Errors

Syntax errors are easy to spot. Usually caused by inputting code incorrectly

eco “<h1>$message</h1>”; Use the line number to find the error and

correct it

QuickTime™ and aTIFF (Uncompressed) decompressor

are needed to see this picture.

Page 32: PHP: Further Skills By Trevor Adams. Topics covered Brief re-cap of core PHP characteristics Arrays Loops Code organisation Error handling Online resources

PHP Errors - Program Errors

These errors occur when a error happens that is generally unforeseen Trying to include a file which does not exist Trying to connect to a database that is offline

Results of functions should generally be checked and handled well Solutions to these issues are often complex We shall return to these errors later in the module

Page 33: PHP: Further Skills By Trevor Adams. Topics covered Brief re-cap of core PHP characteristics Arrays Loops Code organisation Error handling Online resources

PHP Errors - Logical Errors

Hardest type to spot! Typical example is a program script

attempting to divide by zero This could happen in a for loop for example Read the errors on screen

Line numbers are useful Messages are meaningful Take the time to think about the message

Page 34: PHP: Further Skills By Trevor Adams. Topics covered Brief re-cap of core PHP characteristics Arrays Loops Code organisation Error handling Online resources

PHP Errors: Top causes

Typing mistake - check your spelling first Construct improperly closed

E.g. missing a } brace Use comments to help

Missing a semi-colon after a statement Getting the name of a function wrong

E.g. eco “Hello”; Not closing a string

E.g. echo “Hello;

Page 35: PHP: Further Skills By Trevor Adams. Topics covered Brief re-cap of core PHP characteristics Arrays Loops Code organisation Error handling Online resources

PHP Error Handling - overview

Topics covered Why we bother with error handling Types of errors

Notices Syntax Program errors Logical errors

How to handle errors Checking with isset() and empty()

Page 36: PHP: Further Skills By Trevor Adams. Topics covered Brief re-cap of core PHP characteristics Arrays Loops Code organisation Error handling Online resources

Topics covered this lecture

Arrays A type of variable, containing related items Accessed via keys, numerical or textual Values accessed using square [ ] brackets

Code Organisation Why we use functions The ability to include external files

PHP Error Handling Why we bother with errors Different types of errors Top causes of errors

Page 37: PHP: Further Skills By Trevor Adams. Topics covered Brief re-cap of core PHP characteristics Arrays Loops Code organisation Error handling Online resources

Online resources

PHP web site - http://www.php.net/ Contains a searchable database of PHP functions Try searching for ‘sort’ in the ‘function list’

You will be presented with an impressive list of PHP functions involving sorting arrays

Learn to use the PHP manual - it is an invaluable resource for programming PHP.

QuickTime™ and aTIFF (Uncompressed) decompressor

are needed to see this picture.