CHAPTER 3 MORE ON FORM HANDLING INCLUDING MULTIPLE FILES WRITING FUNCTIONS.
-
Upload
tariq-straight -
Category
Documents
-
view
213 -
download
0
Transcript of CHAPTER 3 MORE ON FORM HANDLING INCLUDING MULTIPLE FILES WRITING FUNCTIONS.
CHAPTER 3
MORE ON FORM HANDLING
INCLUDING MULTIPLE FILES
WRITING FUNCTIONS
FORM VALIDATION
Useful functions:Name Description Best use
empty($var) Returns TRUE if the variable has been set and is not NULL
Text input
isset($var) Returns TRUE if the variable hasn't been set, contains a NULL value, or contains an empty string.
Non-text input: radio buttons, check boxes, submit. etc.
is_numeric ($var) Returns TRUE if the variable is a number or a string that can be converted to a number
FORM HANDLING REVISITED
Recall from Chapter 2 form handling with two pages:
One page displays the form
The second page processes it
Instead, both parts can be written into one page with a conditional:
if the form has been submitted
process the data
else
display the form
BOOK EXAMPLE REVISED<?php
// Check for form submission:
if (isset($_POST['submit'])) {
//calculate and print results
} ?>
<h1>Trip Cost Calculator</h1>
<form method="post"> <!-- no action attribute causes form to submit back to same page --> <!-- Display form inputs -->
<input type="submit" name="submit" value="Calculate!">
</form>
Complete code: http://people.uncw.edu/mferner/CSC475/DataFiles/Ch03/calculator.php
REVISED BOOK EXAMPLE WITH FORM VALIDATION// Check for form submission:
if (isset($_POST['submit'])) {
// Minimal form validation:
if (isset($_POST['distance'], $_POST['gallon_price'], $_POST['efficiency']) && is_numeric($_POST['distance']) && is_numeric($_POST['gallon_price']) && is_numeric($_POST['efficiency']) ) {
//calculate and print results
}
else { //invalid inputecho '<h1>Error!</h1><p>Please enter a valid distance, price per gallon, and fuel efficiency.</p>';}
}
Complete code: http://people.uncw.edu/mferner/CSC475/DataFiles/Ch03/calculator_validate.php
STICKY FORMS
The form remembers your previous entries.
• Text input: use the value attribute to print the variable if it exists.
• Radio buttons or check-boxes: add the code checked="checked" to the input tags if that value was selected.
• Textarea input: since there is no value attribute, just print the variable (if it is empty, nothing will show.)
• To preset a selection list, use the selected attribute.
Complete code:http://people.uncw.edu/mferner/CSC475/DataFiles/Ch03/calculator_sticky.php
INCORPORATING EXTERNAL FILES
include() and require() are equivalent when there are no problems – they differ in how they handle errors:
• include() – if include() fails, a warning will display, but the script will continue to run
• require() – if require() fails, and error is displayed, and the script is halted
Relative or absolute referencing may be used – relative is preferable
include_once() and require_once() are available for more complex code but cause extra work and thus potential slow-downs
ABSOLUTE VS RELATIVE PATHS• An absolute path references a file starting from the root
directory of the server:
include('C:/php/includes/file.php');
include('/usr/home/public_html/php/includes/file.php');
• A relative path uses the referencing (parent) file as the starting point.
• It will remain accurate even if the site is moved to another server.
• To move up one folder, use two periods
• To move into a folder, use its name followed by /
include('../ex2/file.php');
SEPARATING PAGE PARTS
header.html
footer.html
index.php
A SIMPLE FILE STRUCTURE
index.phpincludes(folder)
header.html
footer.html
style.css
images(folder)
MORE COMPLEX FILE STRUCTURES
Use MVC pattern:
• Model: contains files that manage the data or that interface with the database
• View: contains the files that represent the user interface
• Controller: contains files that receive the HTTP requests from browsers
www.sitepoint.com
USER-DEFINED FUNCTIONS• Function names are case insensitive (unlike variable
names)
• Syntax:
function function_name() {
// function code
}
• Uses
• associate repeated code with one function call• separate out sensitive or complicated processes from
other code• make common code bits easier to reuse
FUNCTIONS AND ARGUMENTS EXAMPLEUse a function to create the radio buttons in the car calculator program:
// This function creates a radio button.
// The function takes one argument: the value.
// The function also makes the button "sticky".
function create_gallon_radio($value) {
// Start the element:
echo '<input type="radio" name="gallon_price" value="' . $value . '"';
// Check for stickiness:
if (isset($_POST['gallon_price']) && ($_POST['gallon_price'] == $value)) {
echo ' checked="checked"';
}
echo " /> $value "; // Complete the element
} // End of create_gallon_radio() function.
CALLING THE FUNCTION<form action="calculator.php" method="post">
<p>Distance (in miles): <input type="text" name="distance" value="<?php if (isset($_POST['distance'])) echo $_POST['distance']; ?>" /></p>
<p>Ave. Price Per Gallon:
<?php
create_gallon_radio('3.00');
create_gallon_radio('3.50');
create_gallon_radio('4.00');
?>
</p>
…
RETURNING VALUES FROM FUNCTIONSPHP functions may or may not return values
print will return a 1 (success) or a 0 (fail)
echo does not return anything
Use return()
Example:
function calculate_trip_cost($miles, $mpg, $ppg) {
// Get the number of gallons:
$gallons = $miles/$mpg;
// Get the cost of those gallons:
$dollars = $gallons/$ppg;
// Return the formatted cost:
return number_format($dollars, 2);
} // End of calculate_trip_cost() function.