1 PHP and MySQL David Lash Module 2 Working with forms, PHP conditionals and loops.
PHP: Further Skills By Trevor Adams. Topics covered Brief re-cap of core PHP characteristics Arrays...
Transcript of PHP: Further Skills By Trevor Adams. Topics covered Brief re-cap of core PHP characteristics Arrays...
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
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]
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”;
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
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
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
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
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!
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)…
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
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
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
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
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
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
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
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
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
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
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>”; }
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>
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.
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
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
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
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
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.
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
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.
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
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
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;
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()
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
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.