Más contenido relacionado



  1. PHP Workshop ‹#› Forms (Getting data from users)
  2. PHP Workshop ‹#› Forms: how they work • We need to know.. 1. How forms work. 2. How to write forms in XHTML. 3. How to access the data in PHP.
  3. PHP Workshop ‹#› How forms work Web Server User User requests a particular URL XHTML Page supplied with Form User fills in form and submits. Another URL is requested and the Form data is sent to this page either in URL or as a separate piece of data. XHTML Response
  4. PHP Workshop ‹#› XHTML Form • The form is enclosed in form tags.. <form action=“path/to/submit/page” method=“get”> <!–- form contents --> </form>
  5. PHP Workshop ‹#› Form tags • action=“…” is the page that the form should submit its data to. • method=“…” is the method by which the form data is submitted. The option are either get or post. If the method is get the data is passed in the url string, if the method is post it is passed as a separate file.
  6. PHP Workshop ‹#› Form fields: text input • Use a text input within form tags for a single line freeform text input. <label for=“fn">First Name</label> <input type="text" name="firstname" id=“fn" size="20"/>
  7. PHP Workshop ‹#› Form tags • name=“…” is the name of the field. You will use this name in PHP to access the data. • id=“…” is label reference string – this should be the same as that referenced in the <label> tag. • size=“…” is the length of the displayed text box (number of characters).
  8. PHP Workshop ‹#› Form fields: password input • Use a starred text input for passwords. <label for=“pw">Password</label> <input type=“password" name=“passwd" id=“pw" size="20"/>
  9. PHP Workshop ‹#› Form fields: text input • If you need more than 1 line to enter data, use a textarea. <label for="desc">Description</label> <textarea name=“description” id=“desc“ rows=“10” cols=“30”> Default text goes here… </textarea>
  10. PHP Workshop ‹#› Form fields: text area • name=“…” is the name of the field. You will use this name in PHP to access the data. • id=“…” is label reference string – this should be the same as that referenced in the <label> tag. • rows=“…” cols=“..” is the size of the displayed text box.
  11. PHP Workshop ‹#› Form fields: drop down <label for="tn">Where do you live?</label> <select name="town" id="tn"> <option value="swindon">Swindon</option> <option value="london” selected="selected">London</option> <option value=“bristol">Bristol</option> </select>
  12. PHP Workshop ‹#› Form fields: drop down • name=“…” is the name of the field. • id=“…” is label reference string. • <option value=“…” is the actual data sent back to PHP if the option is selected. • <option>…</option> is the value displayed to the user. • selected=“selected” this option is selected by default.
  13. PHP Workshop ‹#› Form fields: radio buttons <input type="radio" name="age" id="u30“ checked=“checked” value="Under30" /> <label for="u30">Under 30</label> <br /> <input type="radio" name="age" id="thirty40" value="30to40" /> <label for="thirty40">30 to 40</label>
  14. PHP Workshop ‹#› Form fields: radio buttons • name=“…” is the name of the field. All radio boxes with the same name are grouped with only one selectable at a time. • id=“…” is label reference string. • value=“…” is the actual data sent back to PHP if the option is selected. • checked=“checked” this option is selected by default.
  15. PHP Workshop ‹#› Form fields: check boxes What colours do you like?<br /> <input type="checkbox" name="colour[]" id="r" checked="checked" value="red" /> <label for="r">Red</label> <br /> <input type="checkbox" name="colour[]" id="b" value="blue" /> <label for="b">Blue</label>
  16. PHP Workshop ‹#› Form fields: check boxes • name=“…” is the name of the field. Multiple checkboxes can be selected, so if the button are given the same name, they will overwrite previous values. The exception is if the name is given with square brackets – an array is returned to PHP. • id=“…” is label reference string. • value=“…” is the actual data sent back to PHP if the option is selected. • checked=“checked” this option is selected by default.
  17. PHP Workshop ‹#› Hidden Fields <input type="hidden" name="hidden_value" value="My Hidden Value" /> • name=“…” is the name of the field. • value=“…” is the actual data sent back to PHP.
  18. PHP Workshop ‹#› Submit button.. • A submit button for the form can be created with the code: <input type="submit" name="submit" value="Submit" />
  19. PHP Workshop ‹#› Fieldset • In XHTML 1.0, all inputs must be grouped within the form into fieldsets. These represent logical divisions through larger forms. For short forms, all inputs are contained in a single fieldset. <form> <fieldset> <input … /> <input … /> </fieldset> <fieldset> <input … /> <input … /> </fieldset> </form>
  20. PHP Workshop ‹#› In PHP… • The form variables are available to PHP in the page to which they have been submitted. • The variables are available in two superglobal arrays created by PHP called $_POST and $_GET.
  21. PHP Workshop ‹#› Access data • Access submitted data in the relevant array for the submission type, using the input name as a key. <form action=“path/to/submit/page” method=“get”> <input type=“text” name=“email”> </form> $email = $_GET[‘email’];
  22. PHP Workshop ‹#› A warning.. NEVER TRUST USER INPUT • Always check what has been input. • Validation can be undertaken using Regular expressions or in-built PHP functions.
  23. PHP Workshop ‹#› A useful tip.. • I find that storing the validated data in a different array to the original useful. • I often name this array ‘clean’ or something similarly intuitive. • I then *only* work with the data in $clean, and never refer to $_POST/$_GET again.
  24. PHP Workshop ‹#› Example $clean = array(); if (ctype_alnum($_POST['username'])) { $clean['username'] = $_POST['username']; }
  25. PHP Workshop ‹#› Filter example $clean = array(); if (ctype_alnum($_POST['username'])) { $clean['username'] = $_POST['username']; } $clean = array(); Initialise an array to store filtered data.
  26. PHP Workshop ‹#› Filter example $clean = array(); if (ctype_alnum($_POST['username'])) { $clean['username'] = $_POST['username']; } if (ctype_alnum($_POST['username'])) Inspect username to make sure that it is alphanumeric.
  27. PHP Workshop ‹#› Filter example $clean = array(); if (ctype_alnum($_POST['username'])) { $clean['username'] = $_POST['username']; } $clean['username'] = $_POST['username']; If it is, store it in the array.
  28. PHP Workshop ‹#› Is it submitted? • We also need to check before accessing data to see if the data is submitted, use isset() function. if (isset($_POST[‘username’])) { // perform validation }
  29. PHP Workshop ‹#› PHP: Moving On..
  30. PHP Workshop ‹#› Expressions and Operators
  31. PHP Workshop ‹#› Reminder • PHP is embedded within xhtml pages within the tags: <?php … ?> • The short version of these tags can also be used: <? … ?> • Each line of PHP is terminated, like MySQL, with a semi-colon.
  32. PHP Workshop ‹#› Reminder • Variables are automatically initialised when you start to use them. e.g. <?php $name = ‘Rob’; echo $name; ?>
  33. PHP Workshop ‹#› Expressions • Using variables within expressions to do something is what PHP is all about. <?php $name = ‘Rob’; echo $name; ?> Expression Operator
  34. PHP Workshop ‹#› Some Types of Operator • Arithmetic • Assignment • Bitwise • Comparison • Ternary • Incrementing /decrementing • Logical • String
  35. PHP Workshop ‹#› String Operators • Use a dot to concatenate two strings: e.g. $firstname = ‘Rob’; $surname = ‘Tuley’; // displays ‘Rob Tuley’ echo $firstname.’ ‘.$surname;
  36. PHP Workshop ‹#› Arithmetic Operators Example Name Result $a + $b Addition Sum of $a and $b. $a - $b Subtraction Difference of $a and $b. $a * $b Multiplication Product of $a and $b. $a / $b Division Quotient of $a and $b. $a % $b Modulus Remainder of $a divided by $b.
  37. PHP Workshop ‹#› Assignment Operators Example Result $a = $b Sets $b to the same value as $a. $a += $b Equivalent to $a = $a + $b. $a .= $b Equivalent to $a = $a.$b.
  38. PHP Workshop ‹#› Combining Operators • Note that you can combine operators, for example use =, + and / in one expression: $a = 4; $b = 2; $c = $a + $b + ($a/$b); // $c has value 4+2+(4/2) = 8 • Brackets help group operators.
  39. PHP Workshop ‹#› Comparison Operators Example Name Result $a == $b Equal TRUE if $a is equal to $b. $a != $b Not equal TRUE if $a is not equal to $b. $a <> $b Not equal TRUE if $a is not equal to $b. $a < $b Less than TRUE if $a is strictly less than $b. $a > $b Greater than TRUE if $a is strictly greater than $b. $a <= $b Less than or equal to TRUE if $a is less than or equal to $b. $a >= $b Gtr than or equal to TRUE if $a is greater than or equal to $b.
  40. PHP Workshop ‹#› Comparisons • Comparison expressions return a value of TRUE (or ‘1’) or FALSE (or ‘0’). e.g. $a = 10; $b = 13; // result is true (‘1’) echo $a < $b;
  41. PHP Workshop ‹#› Incrementing/Decrementing Example Name Effect ++$a Pre-increment Increments $a by one, then returns $a. $a++ Post-increment Returns $a, then increments $a by one. --$a Pre-decrement Decrements $a by one, then returns $a. $a-- Post-decrement Returns $a, then decrements $a by one.
  42. PHP Workshop ‹#› Logical Operators Example Name Result $a and $b And TRUE if both $a and $b are TRUE. $a or $b Or TRUE if either $a or $b is TRUE. $a xor $b Xor TRUE if either $a or $b is TRUE, but not both. !$a Not TRUE if $a is not TRUE. $a && $b And TRUE if both $a and $b are TRUE. $a || $b Or TRUE if either $a or $b is TRUE.
  43. PHP Workshop ‹#› Finally, a tricky one! • A single ? is the ternary operator. (expr) ? if_expr_true : if_expr_false; • A test expression evaluates to TRUE or FALSE. •TRUE gives first result (before colon) •FALSE gives second result (after colon)
  44. PHP Workshop ‹#› Ternary Operator example <?php $a = 10; $b = 13; echo $a<$b ? ‘a smaller’:‘b smaller’; // string ‘a smaller’ is echoed // to the browser.. ?>
  45. PHP Workshop ‹#› Groups of variables • So far, we have stored ONE piece of data in each variable. • It is also possible to store multiple pieces of data in ONE variable by using an array. • Each piece of data in an array has a key..
  46. PHP Workshop ‹#› An array Normal Variable, no key: $name = ‘Rob’; Array Variable, multiple pieces with ‘keys’: $name[0] = ‘Rob’; $name[1] = ‘Si’; $name[2] = ‘Sarah’; … The ‘key’
  47. PHP Workshop ‹#› Array keys • Array keys can be strings as well as numbers.. $surname[‘rob’] = ‘Tuley’; $surname[‘si’] = ‘Lewis’; • Notice the way that the key is specified, in square brackets following the variable name.
  48. PHP Workshop ‹#› Working with arrays.. • Create Array (automatic keys): $letters = array('a','b','c','d'); The array keys are automatically assigned by PHP as 0, 1, 2, 3 i.e. $letters[1] has value ‘b’ • Create Array (explicit keys): $letters = array(10=>’a’,13=>’b’); i.e. $letters[13] has value ‘b’
  49. PHP Workshop ‹#› Working with arrays… • Create array (component by component): $letters[10] = ‘a’; $letters[13] = ‘b’; • Access array component: echo $letters[10]; // displays a echo $letters[10].$letters[13]; // displays ab
  50. PHP Workshop ‹#› Working with arrays… Note that trying to echo an entire array will not display the data. To print an entire array to screen (for debug, for example) use the function print_r instead. echo $letters; print_r($letters);
  51. PHP Workshop ‹#› So.. We know we can: 1. Store things in named variables. 2. Use expressions to operate on the contents of these variables. 3. Can compare variables.. How do we actually include logic in the code such as ‘if this is bigger than that, do this’?
  52. PHP Workshop ‹#› Control Structures • if, elseif, else • while, do … while • for, foreach • switch • break, continue, return • require, include, require_once, include_once
  53. PHP Workshop ‹#› If … • To do something depending on a comparison, use an if statement. if (comparison) { expressions; // do if TRUE } • NB: Notice the curly brackets – these are important!
  54. PHP Workshop ‹#› If example <?php $a = 10; $b = 13; if ($a<$b) { echo ‘a is smaller than b’; } ?>
  55. PHP Workshop ‹#› Extending IF statements • It is possible to add extra optional clauses to if statements.. if (comparison) { expressions; // do if TRUE } else { expressions; // do otherwise }
  56. PHP Workshop ‹#› Extending If statements if (comparison1) { expressions; } elseif (comparison2) { expressions; } else { expressions; }
  57. PHP Workshop ‹#› An example.. $a = 10; $b = 13; if ($a<$b) { echo ‘a is smaller than b’; } elseif ($a==$b) { echo ‘a is equal to b’; } else { echo ‘a is bigger than b’; }
  58. PHP Workshop ‹#› While loops • Might want to do something repeatedly while a comparison is true.. while (comparison) { expressions; }
  59. PHP Workshop ‹#› Example • Lets count to 10! Displays 1,2,3,4,5,..,10: $i = 1; while ($i <= 10) { echo $i++; }
  60. PHP Workshop ‹#› Do .. While • An alternative... $i = 1; do { echo $i++; } while ($i <= 10);
  61. PHP Workshop ‹#› For loop • Sometimes we want to loop around the same bit of code a number of times.. Use a for loop. • for (expr1; expr2; expr3) { statements; } – expr1 evaluated/executed initially – expr2 evaluated at beginning of each iteration (Continues if TRUE) – expr3 evaluated/executed at end of each iteration
  62. PHP Workshop ‹#› For loop example • To count from 1 to 10: for ($i=1; $i<=10; $i++) { echo $i; } initialise Continue if true Execute at end of loop
  63. PHP Workshop ‹#› Foreach loop • A foreach loop is designed for arrays. Often you want to loop through each item in an array in turn.. $letters = array(‘a’,’b’,’c’); foreach ($letters as $value) { echo $value; } // outputs a,b,c in turn
  64. PHP Workshop ‹#› Foreach.. With keys • Sometimes we want to use the array ‘key’ value too: $letters = array(‘a’,’b’,’c’); foreach ($letters as $key => $value) { echo “array $key to $value”; }
  65. PHP Workshop ‹#› Switch statement switch (expr) { case (result1): statements; break; case (result2): statements; break; default: statements; } • expr is evaluated – Case corresponding to result is executed – Otherwise default case is executed • break – Ensures next case isn’t executed
  66. PHP Workshop ‹#› Switch Example switch ($name) { case ‘Rob’: echo ‘Your name is Rob’; break; case ‘Fred’: echo ‘You are called Fred’; break; default: echo ‘Not sure what your name is’; }
  67. PHP Workshop ‹#› break, continue, return • break – Ends execution of current for, foreach, do … while, while or switch structure – Option: Number of nested structures to break out of • continue – Skip rest of current loop – Option: Number of nested loops to skip • return – Ends execution of current function/statement/script
  68. PHP Workshop ‹#› Indentation.. • Code readability IS important – notice how all the code inside a loop/control structure is indented. • Once you start writing nested control loops, indentation is the only way to keep track of your code!
  69. PHP Workshop ‹#› require, include • require('filename.ext') – Includes and evaluates the specified file – Error is fatal (will halt processing) • include('filename.ext') – Includes and evaluates the specified file – Error is a warning (processing continues) • require_once / include_once – If already included won’t be included again
  70. PHP Workshop ‹#› Code Re-use • Often you will want to write a piece of code and re-use it several times (maybe within the same script, or maybe between different scripts). • Functions are a very nice way to encapsulate such pieces of code..
  71. PHP Workshop ‹#› Eh..? What? • You have already used functions.. echo(‘text to display’); Function NAME Function ARGUMENT
  72. PHP Workshop ‹#› What is a function? • A function takes some arguments (inputs) and does something with them (echo, for example, outputs the text input to the user). • As well as the inbuilt PHP functions, we can define our own functions..
  73. PHP Workshop ‹#› Definition vs. Calling There are two distinct aspects to functions: 1. Definition: Before using a function, that function must be defined – i.e. what inputs does it need, and what does it do with them? 2. Calling: When you call a function, you actually execute the code in the function.
  74. PHP Workshop ‹#› Function Definition • A function accepts any number of input arguments, and returns a SINGLE value. function myfunction($arg1,$arg2,…,$argN) { statements; return $return_value; }
  75. PHP Workshop ‹#› Example • Function to join first and last names together with a space.. function make_name($first,$last) { $fullname = $first.’ ‘.$last; return $fullname; }
  76. PHP Workshop ‹#› Calling functions.. • Can be done anywhere.. myfunction($arg1,$arg2,…,$argN) or $answer = myfunction($arg1,$arg2,…,$argN) e.g. echo make_name(‘Rob’,’Tuley’); // echoes ‘Rob Tuley’
  77. PHP Workshop ‹#› Functions: Return Values • Use return() – Causes execution of function to cease – Control returns to calling script • To return multiple values – Return an array • If no value returned – NULL
  78. PHP Workshop ‹#› ‘Scope’ • A function executes within its own little protected bubble, or local scope. • What does this mean? Its means that the function can’t ‘see’ any of the variables you have defined apart from those passed in as arguments.. • Each new function call starts a clean slate in terms of internal function variables.
  79. PHP Workshop ‹#› In other words.. • Variables within a function – Are local to that function • Disappear when function execution ends • Variables outside a function – Are not available within the function • Unless set as global • Remembering variables – Not stored between function calls • Unless set as static
  80. PHP Workshop ‹#› Global variables.. • To access a variable outside the ‘local’ scope of a function, declare it as a global: function add5toa() { global $a; $a = $a + 5; } $a = 9; add5toa(); echo $a; // 14
  81. PHP Workshop ‹#› Static Variables • Local function variable values are not saved between function calls unless they are declared as static: function counter() { static $num = 0; return ++$num; } echo counter(); // 1 echo counter(); // 2 echo counter(); // 3
  82. PHP Workshop ‹#› Default Arguments • Can specify a default value in the function definition which is used only if no value is passed to the function when called.. • Defaults must be specified last in the list function myfunction($arg1,$arg2=‘blah’)… function myfunction($arg1=‘blah’,$arg2)…
  83. PHP Workshop ‹#› Passing References • Pass a reference to a variable – Not the actual variable • Why? – Enables a function to modify its arguments • How? – Use an ampersand in front of the variable – &$variable
  84. PHP Workshop ‹#› Review • More PHP! – Expressions – Operators – Control Structures – Functions