COM336 – Web Database Development XHTML & Forms. PHP and the WWW PHP and HTML forms – Forms are...
-
Upload
alexandrina-carpenter -
Category
Documents
-
view
222 -
download
2
Transcript of COM336 – Web Database Development XHTML & Forms. PHP and the WWW PHP and HTML forms – Forms are...
COM336 – Web Database Development
XHTML & Forms
PHP and the WWW• PHP and HTML forms
– Forms are the main way users can interact with your PHP scrip
• Typical usage of the form tag in HTML– <form id=“formname” action=“URL” method=“”>– </form>
• id is optional (but encouraged in XHTML)• action is mandatory. The value is the URL (or
name of the file, if in current directory) where the data collected by the form is to be sent
• method can take one of two values: get and post2
HTML forms• HTML forms (a way of getting input from the
browser) include form elements such as: – text areas– password areas – check boxes– selection lists– scrolled selection lists– radio buttons– submit button– reset button– picture buttons
3
An HTML form
4
An HTML form
5
Using method=“get”• This method appends the form-data to the URL in
name/value pairshttp://localhost:8080/COM409/receive1.php?email=ytdrtyerh
• This method is useful for form submissions where a user want to bookmark the result (think google search)
• There is a limit to how much data you can place in a URL (varies between browsers), therefore, you cannot be sure that all of the form-data will be correctly transferred
• Never use the "get" method to pass sensitive information! (password or other sensitive information will be visible in the browser's address bar)
6
Using method=“post”• This method sends the form-data as an HTTP
post transaction• Form submissions with the "post" method
cannot be bookmarked (think login forms or member only areas)
• The "post" method is more robust and secure than "get", and
• "post" does not have size limitations
7
PHP Superglobals
• $_GET
• $_POST Works in the same way as $_GET– $_POST is an associative array– The keys to the array are the same as the field names
in your form
– Data sent via post is not exposed to the browser. The transaction is handled internally by the webserver
8
HTML form tags - overview
9
form tag description
<form action="receive.php" method="post"> Start the form
<input type="text" name="name" value="value" size="size"> Text field
<input type="password" name="value" value="value" size="size"> Password field
<input type="hidden" name="name" value="value"> Hidden field
<input type="checkbox" name="name" value="value"> Checkbox
<input type="radio" name="name" value="value"> Radio button
<select name="name" size=1> <option selected>one </option> <option>two </option></select>
Select menu
<select name="name" size=n multiple> Scrolled list
<textarea rows=yy cols=xx name="name"> . . </textarea> Multiline text
<input type="submit" name="name" value="value"> Submit button
<input type="image" src="/image" name="name" value="value"> Image button
<input type="reset" value="message!"> Reset button
</form> Ends form
Starting and ending forms - <FORM> tag
• HTML forms are created by using the HTML <form> and </form> tags
• Within these tags, you place various HTML form elements, such as text areas, check boxes, and radio buttons
<form action=”http://localhost/receive.php” method=”post”>
.
. ---(Your FORM elements here)
. </form>
10
Form arguments
The <form> tag has two primary arguments:• action - Specifies the URL of the PHP script to
start when the form is submitted • method - Defines the format that will be used to
send data to the PHP script– get appends the form arguments to the end of the
Web address (as a Query String after the “?”)– post sends the data as part of the body of the HTTP
Request
11
The <INPUT> tag
• Used to define a range of form elements, designated by its TYPE attribute.
• The general format of the <INPUT> tag is:<input type=“text” name=“element name” value=“default value”>
– type = submit | reset | text | checkbox | radio| etc.– name: will be used by the CGI program to identify the form element (i.e.
the CGI variable)– value: the value to be associated with “name” when processing the form
• (The <input> tag has NO closing tag </input> )
12
The <INPUT> tag - Form buttons
• Used to submit the form or erase all input• When the submit button is clicked, the form
data is sent to the program specified in the ACTION argument, and the CGI program executed
• If form consists only of a submit button, the CGI program is simply executed
13
<INPUT> tag - Text box
• The text input type creates text boxes on forms<input type=”text” size=”15” maxlength=”20” name=”color”>
14
text area box size
max. characters allowed
CGI variable name
<INPUT> tag - Text box
15
Text areas - <TEXTAREA> tag
16
Enables the user to enter multiple lines of text
<textarea rows=10 cols=70 name=“comments” wrap=“virtual”>Please enter comments here</textarea>
The wrap attribute specifies what to do if the user types beyond the right margin of the text area• If omitted, wrapping is not enabled
• If wrap=“virtual”, wrapping is enabled but the text is submitted without linebreaks
• If wrap=“physical”, line breaks are submitted as part of the text
CGI variable name
default text value
<INPUT> tag - Checkboxes
17Copyright © 2002 Pearson Education, Inc.
<INPUT> tag - Checkboxes
• Small boxes on a form that create a check mark when the user clicks them
<input type=”checkbox” name=”usa” value=”yes”> USA <input type=”checkbox” name=”china” value=”yes” checked> China
• The user may select (tick) multiple boxes
18
CGI variable name
CGI variable value when clicked
label displayed next to checkbox
<INPUT> tag - Radio buttons
19Copyright © 2002 Pearson Education, Inc.
Radio buttons - <INPUT> tag
• Small circles that operate similarly to checkboxes, except that only one button within the group can be selected at any given time
<INPUT TYPE="radio" NAME="payment" VALUE="visa" checked > Visa
<INPUT TYPE="radio" NAME="payment" VALUE="amex"> American Express
<INPUT TYPE="radio" NAME="payment“ VALUE="mastercard"> Mastercard
20
CGI variable name
CGI variable value
label displayed next to radio button
<SELECT> tag - Selection lists
• Used to create a list for user to choose from , either as a drop-down menu or a scrolling box:
<select name=“platform” size=1><option selected>Win95</option><option>Win98</option><option>Win2k</option><option>linux</option></select>
• For a scrolling box, specify SIZE greater than one. e.g. SIZE = 3 will generate a scrolling windows 3 rows high
21
CGI variable name
list items that user can select CGI variable value
Form generation using PHP - Example
22
Form generation using PHP - Example - output
23
Example form
Selection list
Radio buttons
Text box
Text area
Text box
Submit button
PHP Same Page Processing
• A form can be sent to a different PHP page for processing, or can be processed on the same page.
• The action property of the form will determine who processes the form
• In order for a form to be processed on the same page, the page will have to be a PHP page and you will need to check for the submit button to be pressed. (not empty) – Also the Action of the form can be set to the same page or left empty.
Example
<form name="mailinglist" method="post"><input type="text" name="email" /><input type="submit" name="mailing-submit" value="Join Our Mailing List" /></form>
<?php if (!empty($_POST['mailing-submit'])) { //Code to be executed upon processing the form;}?>
Adapted From: BAVOTA, C. (2009) Processing Multiple Forms on One Page with PHP [ONLINE]URL: http://bavotasan.com/2009/processing-multiple-forms-on-one-page-with-php/
It is a good idea to kill the script if the form is not filledby checking for set variablesafter the submit button is pressed
ExampleMultiple Forms
Adapted From: BAVOTA, C. (2009) Processing Multiple Forms on One Page with PHP [ONLINE]URL: http://bavotasan.com/2009/processing-multiple-forms-on-one-page-with-php/
<form name="mailinglist" method="post"><input type="text" name="email" /><input type="submit" name="mailing-submit" value="Join Our Mailing List" /></form> <form name="contactus" method="post"><input type="text" name="email" /><input type="text" name="subjet" /><textarea name="message"></textarea><input type="submit" name="contact-submit" value="Send Email" /></form>
Multiple FormProcessing – Same Page
<?php if (!empty($_POST['mailing-submit'])) { //do something here to process the first form;} if (!empty($_POST['contact-submit'])) { //do something here to process the second form}?>
Adapted From: BAVOTA, C. (2009) Processing Multiple Forms on One Page with PHP [ONLINE]URL: http://bavotasan.com/2009/processing-multiple-forms-on-one-page-with-php/
PHP – User Defined Functions
Functions
• Functions are self-contained units of a program designed to accomplish a specified task such as calculating a mortgage payment, retrieving data from a database, or checking for a valid input
• PHP provide a good number of built-in functions and we have seen some of them, but there is a time when the built in functions are no longer capable of accomplishing your programming goals – that’s when we start coding user defined functions
Functions
• By definition a function is a block of statements that not only perform some task, but can also return a value.
• A function is independent of the program and is not executed until called
Declaration, Definition and Invocation
• Declaration: Is to give it a name along with the keyword function and a set of parenthesis that might contain parameters(arguments) that the function will accept.
• Definition: It’s the declaration AND the body of statements found within the curly braces after the function’s declaration
• Invocation: Refers to calling the function (tells PHP to start executing the statements withing the curly braces
Declaration, Definition and Invocation
function do_something() // Declaration
function do_something() {statement1; // Definitionstatement2;
}
do_something(); // Invocation
Where to Put Them
• Commonly used functions are often stored in separate fules to reuse as needed (using include or require PHP functions to load them)
• They can also be declared anywhere within a file and they are available only to the script where they are defined.
• Functions can be called before or after its definition (PHP internally compiles all function definitions before executing the statements in the script)
Function Example
• The following function Prints a custom message to the screen.
• Note that within curly braces, any legal PHP code is accepted, including other functions, calls, HTML, declaration of new variables, even calls to itself.
<?phpfunction bye() {
print "Bye, Adios, Au Revoir, Adieu, fo, do svidaniya";}?>
Naming Conventions
• Function, like variables, has naming conventions:1. It must consist of letters, digits, or the
underscore and cannot begin with a digit.2. The name must be unique for each function.3. It should be given a name that indicates its
purpose with an action word or a verb.4. Function names are NOT case sensitive.
Convention uses lowercase names.
Passing Arguments
• To send values to a function, it must be called (and defined) with a comma-separated list of arguments enclosed in parenthesis.
• The Arguments can be a combination of numbers, strings, references, variables etc.
• There are two ways of passing parameters to a function: by value and by reference
Passing Parametersby VALUE
• When passing a parameter by value, PHP makes a copy of the variable, so that if the function changes it inside the function, only the copy is being changed.
• When the function exits, the copy is destroyed.
• This is considered a safe way to pass arguments and is designed to be the default.
ExampleCalculate Volume:
The Form<html><head><title>Passing Arguments</title></head><body bgcolor="lavender"><form action="volume.php" method="get"><p>Find the volume (in feet) of a rectangular room with sides <input type="text" size=6 name="s1">by<input type="text" size=6 name="s2">by<input type="text" size=6 name="s3"></p><p><input type="submit" name="submit" value="Get Volume" ></form></p></body></html>
The PHP<?phpextract($_REQUEST); //$_REQUEST is an associative array that by default contains the contents of $_GET, $_POST and $_COOKIE.volume($s1, $s2, $s3); // Passing 3 arguments and calling the function
function volume($side1,$side2,$side3){ print "The volume of the room is: " . $side1 * $side2 * $side3."cubic ft.<br>"; }?>
Passing ParametersBy REFERENCE
• Only variables can be passed by reference.
• When passing values by reference, the function can change the value of the parameter being passed.
• To pass a parameter by reference, the variable being passed is preceded by the symbol ‘&’ in the function declaration line.
ExampleParameters by Reference
function html_tags(&$text, $tags="pre"){
switch($tags){ case 'br': $text = "$text</$tags>"; break; case 'p': $text = "<$tags>$text</$tags>"; break; default: $text = "<$tags>$text</$tags>"; break; } }
This function receives 2 arguments:$text is passed by reference so thefunction will modify it
$tags is passed as a value and it has a DEFAULT VALUE (pre)
This function will format the stringwith the appropriate HTML tag in the appropriate place
ExampleParameters by Reference
Firs Call Example:
$colors = array('red','green','blue'); $list=print_r ($colors,true); html_tags($list); echo "$list";
An array with 3 colors
print_r will print the contentsof the argument variable and save it to the variable $list
then the function html_tags is calledwith only 1 argument, the list;
the second parameter will take the valueof PRE which is the DEFAULT
<pre>Array( [0] => red [1] => green [2] => blue)</pre>
Browser OutputBrowser Code View
ExampleParameters by Reference
Second Call Example:
the string “Hello World” is going to be formatted here with <p> tags
so the “p” tag is passed by value andthe $string by reference;
the functions changes the string byadding the <p> tags.
notice the code view returned by the browser and the spacing in the browser output
$string = "Hello, world!"; html_tags($string,"p"); echo "$string"; echo "$string";
<p>Hello, world!</p><p>Hello, world!</p>
Browser OutputBrowser Code View
Returning Values
• Most of the time, a function will be constructed to make a calculation and return a value
• The RETURN statement in a functions allows the function to send a value back to the caller or to exit the function before it reaches the end.
Example - Return<?php $grades=array(40,90,89,93,75); $result = average($grades); // Pass an array print "The average grade is $result.<br>"; function average($scores){ $sum = 0; $size = count($scores); // Find the size of the array if ( $size == 0 ){ echo "Empty parameter list<br>"; die(); } // Exit the script here – exit(); can also be used here. for($i = 0; $i < $size; $i++){ $sum += $scores[$i]; //sums each score to the total ($sum) and stores in $sum } return $sum/$size; // Return the average}?>