What We Will Cover
Elucidations
Homework Questions?
Quiz Questions?
^ top
7.1: Working with PHP Strings
Objectives
At the end of the lesson the student will be able to:
- Create and manipulate strings
|
^ top
7.1.1: String Literals and Variables
- Forms return their data as string values
- Thus, we need to understand how to use strings if we want to work with form data
Creating String Literals and Variables
- String literals are made by enclosing a sequence of characters in double quotes
- For example:
"abc" "b" "3.14159" "$3.95" "My name is Ed"
Notice that the string "3.14159" could be expressed as a number by removing the quotes
Variables can be assigned string values
$name = "Ed";
Here the variable $name gets assigned the string "Ed"
Mixing Strings and Numbers
- Unlike numeric variables, you cannot add, subtract, multiply or divide strings
- Thus, must be careful when mixing string and numeric expressions
- What, if anything, is displayed by the following PHP code?
$fruit = "apple"
$sum = $fruit + 1;
print "Sum = $sum";
As an experienced programmer, you may expect an error message
Instead, PHP will display the output:
Sum = 1
This is because PHP automatically converts strings to numbers
If the string is not in a number format, the result is returned as 0
As another example, what is displayed by the following?
<?php
$num = "3.14159" + 1;
print $num;
?>
^ top
7.1.2: Concatenating Strings
- One of the ways to manipulate strings is concatenation
- Concatenation joins two strings into one string using the "dot" (
.) operator
$message = "PHP" . " " . "rules!"
The above concatenates the three strings into one string: "PHP rules!"
Then assigns the single string to the variable $message
Now print the variable to see the result of the concatenation
print "Message = $message";
Will output the line
Message = PHP rules!
^ top
7.1.3: Using String Functions
- Many applications need to use string manipulation functions
- These functions perform some operation and return a value
- Some of the operations that string functions perform are:
- Determine the length of a string
- Remove leading spaces
- Convert a string to upper or lower case
- Get part of a string
- We will look at how to use some of the many string functions
- For a complete list, see: String functions
Arguments
- Most string functions require you to send them one or more arguments
- Arguments are input values that functions use in processing
- Often functions return a value based on the arguments
- Can see an example of this in the
strlen function that follows
^ top
7.1.4: The strlen Function
- Used to determine the length of a string
- General syntax:
int strlen(string)
For example:
$message = "PHP rules!";
$len = strlen($message);
print "Length of '$message' is $len";
Displays the output
Length of 'PHP rules!' is 10
^ top
7.1.5: The trim Function
- Used to remove the leading and trailing spaces from a string
- General syntax:
string trim(string)
For example:
$message = " PHP rules! ";
$message = trim($message);
print "'$message'";
Displays the output
'PHP rules!'
^ top
- Used to change the case of strings
- General syntax:
string strtolower(string)
string strtoupper(string)
For example:
$message = "PHP rules!";
$lower = strtolower($message);
$upper = strtoupper($message);
print "Lower=$lower and upper=$upper";
Displays the output
Lower=php rules! and upper=PHP RULES!
^ top
7.1.7: The substr Function
- Used to get part of a string
- General syntax:
string substr(string, start [, length])
For example:
$date = "12/25/2004";
$month = substr($date, 0, 2);
$day = substr($date, 3, 2);
$year = substr($date, 6);
print "Month=$month, day=$day and year=$year";
Displays the output
Month=12, day=25 and year=2005
Using a Negative Starting Value
- A negative value for the
start argument changes the direction
- Starts counting from the right instead of the left
- For example:
$filename = "myfile.php";
$suffix = substr($filename, -3);
print "Suffix=$suffix";
Displays the output
Suffix=php
^ top
7.1.8: Summary
- String literals are made by enclosing a sequence of characters in double quotes
- When you mix strings with numbers, you may get incorrect results
- PHP will attempt to convert strings to numbers in numeric contexts
- If it cannot convert, the string is assigned the numeric value 0
- Concatenation joins two strings into one string using the "dot" '.' operator
- PHP has many function designed to work with strings
| Function |
Purpose |
| strlen() |
Used to determine the length of a string. |
| trim() |
Used to remove the leading and trailing spaces from a string. |
| strtolower() |
Used to change the case of a string to lower case. |
| strtoupper() |
Used to change the case of a string to upper case. |
| substr() |
Used to extract part of a string. |
^ top
Exercise 7.1
With your partner, take 5 minutes to complete the following:
- Start a text file named exercise7.txt.
- Prepare the exercise header as described in the HowTo on submitting exercises
- Label this exercise: Exercise 7.1
- Submit all exercises for today's lesson in one file unless instructed otherwise
- Complete the following exercises and answer any questions.
Specifications
- What is displayed by the following PHP script?
$x = 12; $y = 4;
$num = $x + 8 / $y;
print ("Num is $num but x is $x");
- What is displayed by the following PHP script?
$file = " data.txt";
$short = trim($file);
$part1 = substr($short, 0, 4);
$part2 = substr($short, -3);
print ("part1=$part1 and part2=$part2");
- Write a script to convert a date string, such as the following, into a nicely formatted date like 10-23-2003.
$date = "20031023";
Copy the completed script into your exercise7.txt file.
^ top
7.2: Using HTML Input Forms
Objectives
At the end of the lesson the student will be able to:
- Create HTML input forms
- Pass data from HTML forms to PHP scripts
|
^ top
7.2.1: Getting Started with HTML Forms
About HTML Forms
- So far, our PHP scripts have not been able to get input from the user
- HTML forms give us a way to ask the user for values
- These values can then be read inside our PHP scripts
- We will look at several HTML form input elements in this lesson
Constructing Forms
- You construct a basic HTML form like this:
<form> |
Begin a form |
<input> |
Ask the user for information in one of several ways |
<input> |
You can have as many input areas as you want |
</form> |
End a form |
Starting the Form
- You start an HTML form within the
<form> tag
<form action="myscript.php" method="post">
The form tag has two primary arguments
action specifies the URL of the script to send the information to
- Can use absolute or relative addresses
method specifies how to send the information
- The
get method appends the information to the URL
- The
post method sends the data within the body of the request
- You usually use the
post method
^ top
7.2.2: Creating Form Buttons
- Most forms need at least one button
<input name="myname" type="submit" value="Click to Submit">
- The button lets the user to submit the form data to a script
- An optional
name field allows you to give the button a name
- Important for telling the difference between multiple buttons
- You will use the name attribute often in your PHP code
- A
type argument specifies the button type
- The
value argument provides the label for the button
- Another useful button is the reset button
<input type="reset" value="Erase and Restart">
This button allows the user to clear all the data in the form
For Example
- Here is a more complete example:
1
2
3
4
5
6
7
8
9
10
|
<html>
<head> <title>Login Form</title> </head>
<body>
<form action="echo.php" method="post" >
Here are two buttons to click.
<br> <input type="submit" value="Click To Submit">
<input type="reset" value="Erase and Restart">
</form>
</body>
</html>
|
^ top
7.2.3: Creating Text and Password Boxes
<input type="text" size="15" maxlength="20" name="login">
<input type="password" size="15" maxlength="20" name="pwd">
type="text" says to create a text field
- An optional
size specifies the width of the text box
- An optional
maxlength specifies the maximum number of input characters
- An optional
name allows the receiving script to identify the form element
- Note that
text and password boxes are not secure methods for transmitting data
- Data is sent in clear text like any other HTML data
- You need to use additional techniques to secure the transmission of data
For Example
- Here is a more complete example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
<html>
<head> <title>Login Form</title> </head>
<body>
<h1>Please Login</h1>
<form action="echo.php" method="post" >
<p>Username:
<input type="text" size="15" maxlength="20" name="login">
<br>Password:
<input type="password" size="15" maxlength="20" name="pwd">
</p>
<br> <input type="submit" value="Click To Login">
<input type="reset" value="Erase and Restart">
</form>
</body>
</html>
|
^ top
7.2.4: Creating Text Areas
- Text areas are like text boxes except you can have multiple lines
<textarea rows="4" cols="50" name="Comments">
Your comments here
</textarea>
The rows attribute sets the number of lines
The cols attribute sets the number of columns
An optional name allows the receiving script to identify the form element
Text areas also need a closing tag
Any text between the tags appears as the initial default text
^ top
7.2.5: Creating Radio Buttons
- Radio buttons provide a list of choices with a "button" to click
<input type="radio" name="sex" value="male" checked> Male
<input type="radio" name="sex" value="female"> Female
A user can check only one button at a time
You specify the element with type="radio"
Notice that both name attributes are the same
- You only expect one value from many radio buttons
Optional checked attributes selects the initial button
^ top
7.2.6: Creating Check Boxes
- Check boxes are similar to radio buttons but are used to select individual items
I like:
<input type="checkbox" name="php" value="1" checked> PHP
<input type="checkbox" name="java" value="2"> Java
You specify the element with type="checkbox"
name allows the receiving script to identify the form element
Optional checked attribute pre-selects the item
^ top
7.2.7: Creating Selection Lists
- Selection lists create a box combined with a list of items
- The user can scroll through the list and select an item
<select name="state" size=2 multiple>
<option value="CA">California
<option value="OR" selected>Oregon
<option value="WA">Washington
</select>
The name attribute allows the receiving script to identify the form element
An optional size sets the height of the viewable window
An optional multiple allows the user to select more than one item
- Using the Control or Shift keys while clicking
The text between option tags is displayed in the select list
An optional selected argument pre-selects the item
^ top
7.2.8: Receiving Form Data in PHP Scripts
- PHP makes it easy to receive input data from forms
- For instance, given the following input element
<input type=checkbox name="single">
We use $_REQUEST with square brackets and the element name like this:
$single = $_REQUEST["single"];
print "single = $single";
If you only want to accept data passed using the GET method, use $_GET instead
$single = $_GET["single"];
print "single = $single";
If you only want to accept data passed using the POST method, use $_POST instead
$single = $_POST["single"];
print "single = $single";
We will explore this process in more depth in the next exercise
Superglobal Arrays Used with Forms
| Array |
Description |
| $_GET |
Access to variables passed via the HTTP GET method. |
| $_POST |
Access to variables passed via the HTTP POST method. |
| $_REQUEST |
Access to variables passed via both the HTTP GET and POST methods. |
^ top
Exercise 7.2
Instructions:
In this exercise we explore how to get form data into our PHP scripts for processing.
- Label this exercise: Exercise 7.2
- Submit all exercises for today's lesson in one file unless instructed otherwise
- Complete the following exercises.
Exercises and Questions
- Create an HTML page by copying the following code into a text editor
- Save the file as formget.html in your
/home/cis165/public_html directory
<html>
<head>
<title>Input Form</title>
</head>
<body>
<h2>A simple input form</h2>
<form method="get" action="formecho.php">
<p>Please enter the supplier name
<input type="text" name="supplierName" size="20"></p>
<p>Please enter the supplier code
<input type="text" name="supplierCode" size="10"></p>
<input type=submit name="submit" value="Submit">
<input type=reset value="Reset">
</form>
</body>
</html>
- Create a new PHP script by copying the following code into a text editor
- Save the file as formecho.php.
<html>
<head>
<title>Form Echo</title>
</head>
<body>
<h2>Form Echo</h2>
<?
$supplierName = $_REQUEST["supplierName"];
print "supplierName = $supplierName";
$supplierCode = $_REQUEST["supplierCode"];
print "<br>supplierCode = $supplierCode";
$submit = $_REQUEST["submit"];
print "<br>submit = $submit";
?>
</body>
</html>
- Run the formget.html file on your localhost server
Q1: What parameters and values do you see in the URL of formecho.php when using method="GET"?
- Create a new HTML page using formget.html, changing the form method from "GET" to "POST" and then saving the file as formpost.html.
- Run the formpost.html file on your localhost server
Q2: Do you still see parameters and values in the URL of formecho.php? Why not?
- Staying with your formecho.php page, add the following CGI parameter and value in the address bar and press enter.
http://localhost/~cis165/formecho.php?supplierName=YetAnother
Q3: Do you see the CGI values displayed in your script? Why?
Q4: Can you use a hyperlink to pass data to a script? Why or why not?
^ top
7.3: Saving Form Data in MySQL
Objectives
At the end of the lesson the student will be able to:
- Save data from HTML forms in MySQL
|
^ top
7.3.1: Inserting Data into MySQL
- Since you can get form data, you can enter it into a database
Steps for Inserting Data
- Create a connection and select a database.
require_once("includes/dbconvars.php");
$dbCnx = mysql_connect($dbhost, $dbuser, $dbpwd);
mysql_select_db($dbname, $dbCnx);
- Save the
$_REQUEST values in a variable like this:
$supplierName = $_REQUEST["supplierName"];
$supplierCode = $_REQUEST["supplierCode"];
- Code a SQL INSERT statement using the variables in a string like this:
$sql = "
INSERT INTO suppliers VALUES
(NULL, '$supplierName', '$supplierCode')
";
print "<p>$sql</p>\n";
Note that you can have extra whitespace in PHP strings. This can make formatting your SQL statements easier.
Also note that the SQL statement should not contain a semicolon (according to the PHP manual) though you still need a semicolon at the end of the PHP statement.
In addition, it is a good practice to print your SQL statement for verification and debugging. You can remove the print statement when the query works correctly.
- Execute your SQL query and check the results.
mysql_query($sql) or die("Query failed: ".mysql_error());
Note that the result of an INSERT operation is TRUE on success and FALSE on error.
- If you want to find out how many rows were affected, use the mysql_affected_rows() function.
$numRows = mysql_affected_rows();
print "Rows affected: $numRows\n";
^ top
7.3.2: Saving Data in Two Tables
- Saving related data in two tables is more complicated than saving in one table
- You need the primary key of the row from the first table for use in the second table
- Because the primary key is the foreign key of the second table
- Recall that MySQL has a function called
LAST_INSERT_ID()
- Returns the last automatically generated value inserted into an AUTO_INCREMENT column
- If many rows are inserted at the same time, it returns the ID of the first insertion
- PHP has a similar command called mysql_insert_id().
- Queries the
LAST_INSERT_ID() MySQL function and returns its value
- You can save the returned value for use as the foreign key in the second table
For Example
$sql = "
INSERT INTO addresses(Address, City, State, Zip, Country)
VALUES ('$address', '$city', '$state', '$zip', '$country')
";
mysql_query($sql) or die("Bad query");
$addressID = mysql_insert_id();
$sql = "
INSERT INTO customers(LName, FName, AddressID, Phone)
VALUES ('$lastName', '$firstName', $addressID, '$phone')
";
mysql_query($sql) or die("Bad query");
Another Technique
- Another technique is to search for the highest AUTO_INCREMENT value after the first INSERT
$sql = "SELECT MAX(ID) FROM Addresses";
$result = mysql_query($sql);
$addressID = mysql_result($result, 0, 0);
This works because AUTO_INCREMENT always returns a higher number for every row inserted
You then use the value extracted from the query as the foreign key in the second table
However, this technique is not as safe as using mysql_insert_id()
The reason is that if you use a SELECT query and someone else inserts a row in the milliseconds between your INSERT and the SELECT, you could get a wrong value returned
On the other hand, the value of mysql_insert_id() is affected only by statements issued within the current client connection
It is not affected by statements issued by other client connections
^ top
7.3.3: Checking and Filtering Input
- One of the largest security exposures for a database is user input
- Users either accidently or maliciously enter incorrect data
- You need to check and filter input before entry into a database
- We have not learned very many PHP tools to perform these checks yet
- We will add techniques to our "toolbox" as we progress through this course
- One tool you do have is PHP's trim function
- Strips whitespace from the beginning and ending of a string
- Sometimes users enter leading or trailing spaces around their data
- SQL queries with extra spaces do not match data that does not have leading or trailing spaces
- To prevent this problem, you can filter user input like this:
$supplierName = trim($supplierName);
$supplierCode = trim($supplierCode);
Since the right-hand is evaluated first, then you can store "trimmed data" in your variables
^ top
7.3.4: Error Levels
- PHP has many levels of error reporting
- When your project is finished, you usually do NOT want to report errors to a user
- However, when you develop scripts you want PHP to show you as many errors as possible
- Having PHP show you the errors makes it easier to find and correct them
- Small problems during development often become big problems when your web application goes into "production"
- To adjust your error levels, you normally change settings in the
php.ini file
- The important settings are shown in the following link:
- Note that the instructor tests your assignments with these
php.ini settings
- If you cannot change the
php.ini file, you can put the following at the top of a script page instead:
<?php
ini_set("display_errors", "1");
error_reporting(E_ALL);
ini_set("register_globals", "0");
?>
- However, putting these lines at the top of the page still will not allow you to see syntax (parse) errors if your
php.ini file is not set correctly
- Thus, if at all possible, change your
php.ini file
More Information
^ top
Exercise 7.3
In this exercise we save form data in a database.
- Label this exercise: Exercise 7.3
- Submit all exercises for today's lesson in one file unless instructed otherwise
- Complete the following exercises and answer any questions.
Exercises and Questions
- Make sure that
dbconvars.php is installed in the includes subdirectory
- Create a new PHP page by copying the following code into a text editor
- Save the file as formdb.php.
<html>
<head>
<title>Supplier Entry Script</title>
</head>
<body>
<h2>Supplier Entry Script</h2>
<?php
require_once("includes/dbconvars.php");
$dbCnx = mysql_connect($dbhost, $dbuser, $dbpwd)
or die("Could not connect: ".mysql_error());
mysql_select_db($dbname, $dbCnx)
or die("Could not select db: ".mysql_error());
$supplierName = $_REQUEST["supplierName"];
$supplierCode = $_REQUEST["supplierCode"];
$sql = "
INSERT INTO suppliers VALUES
(NULL, '$supplierName', '$supplierCode')
";
print "<p>Using SQL:<br>$sql</p>";
mysql_query($sql)
or die("Query failed: ".mysql_error());
print "<p>Rows affected: ".mysql_affected_rows();
mysql_close($dbCnx);
?>
</body>
</html>
- Modify your formget.html page from the last exercise by changing the form
action to formdb.php
<form method="get" action="formdb.php">
- Test the form and script by entering the information for a new supplier and press the Submit button
Examine the artzy database using phpMyAdmin and verify the new data was entered in the suppliers table.
^ top
7.4: Organizing Your Web Application
Objectives
At the end of the lesson the student will be able to:
- Describe how to organize their web application project
- Use
include() and require() functions
|
^ top
7.4.1: About Application Organization
- A web application is a web-based program (such as PHP files) with a user interface
- Managing your PHP web application as it grows can be time consuming
- Unless it is implemented properly from the start
- As web sites grow, they tend to become less organized
- Pieces of code that you use become hard to locate
- When you want to change your site, mysterious bugs appear
- These problem can be avoided with a correct application organization
Files Used in Your Application
- HTML files provide the structure for web documents
- CSS files control the appearance of your pages
- Image files provide graphics and pictures
- PHP provides the logic for your "intelligent" web pages
^ top
7.4.2: Basic Application Structure
- You organize your application code into directories
- Your web-application root should contain all your HTML documents
- HTML documents are usually saved as PHP files
- PHP files providing HTML structure are placed in the
webAppRoot/
- You should place files supporting the HTML document structure in subdirectories
- Reduces the clutter in the
webAppRoot/
- Similarly, you place files supporting PHP in subdirectories
For Example
- I suggest the following structure for your web application
- Only the
includes directory relative to the webAppRoot is required
webAppRoot/
includes/
images/
script/
style/
webAppRoot/: where your web server looks for your application files
- On our classroom system:
/home/cis165/public_html/
- In the CTC:
/home/STUDENT/yourLogin/public_html/
- PHP files providing HTML structure are placed here
You place all other files and folders relative to the webAppRoot
includes/: for files included in your application pages
images/: for files like GIF's and JPEG's
script/: JavaScript files for client-side scripting
style/: for CSS files
You may need other subdirectories depending on you application
Later in the course we will talk about where to place other types of files
Specific Example
- All assignments from now on must be zipped for grading
- When you submit files for grading, you start in the
webAppRoot/
- PHP files specified for assignments must be in the first directory level
- Submit only the files in the
webAppRoot/ and subdirectories
- For example, given the following application structure:
dbform.php
dbentry.php
includes/
dbconvars.php
header.php
footer.php
You zip files starting in the webAppRoot and include all subdirectories
However, you do not include webAppRoot as a folder in your zip file
- You only zip the files in webAppRoot plus all subdirectories and files
In the example dbform.php file above, you require the dbconvars.php file using:
require_once("includes/dbconvars.php");
^ top
7.4.3: Using include() and require()
- To include external files, you use PHP functions
include() and require()
- PHP supports four different functions for including external files
include and require act the same in most ways except how they handle errors
include only issues a warning while require produces a fatal error
include_once and require_once are similar to include and require
- The difference is they will not include code that has already been included previously
- Thus, use
require or require_once to halt processing of the page on error
- Otherwise use
include or include_once
- When files are included, they start out in HTML mode
- Thus, any PHP code must be placed in
<?php ... ?> tags
- Note that you can use a variable to specify the file name
Functions for Including External Scripts
| Function |
Description |
| include |
Includes and evaluates the specified file. Failure during the evaluation produces a warning, which can be suppressed. |
| include_once |
Includes and evaluates the specified file one time only. Failure during the evaluation produces a warning, which can be suppressed. |
| require |
Includes and evaluates the specified file. Failure during the evaluation halts processing of the page. |
| require_once |
Includes and evaluates the specified file one time only. Failure during the evaluation halts processing of the page. |
Caution: Always Append Included Files With .php
- Many Web servers will serve pages ending in
.inc as text
- Thus you should always end your include files with
.php
- Helps prevent accidental exposure of passwords and other sensitive data
^ top
7.4.4: Using include() and require() for Templates
- HTML and PHP code tends to repeat on many pages
- For instance:
- Every well-formed HTML page has opening and closing tags
- Connections to a database are usually made the same way each time
- Rather than write the code on every page, put them into an included file
- This practice allows code to be reused from page to page
- When you need to make changes, you only change the included file
For Example
- If you put the code for the start of a page into a file named
header.php
<html>
<head>
<title><?php echo $title ?></title>
<META name="author" content="Edward Lee Parrish">
<META name="date" content="2004-04-07">
<META name="copyright" content="© 2004 Edward Lee Parrish">
<?php if (isset($other)) echo $other ?>
</head>
<body>
<table width="90%">
<tr>
<td colspan="2">
<img src="images/artzy.gif" alt="Artzy Art Supplies">
</td>
</tr>
<tr><td valign="top" width="15%">
<em>Quick Index</em>
<div id="sidebar">
<a href="index.php">Home</a>
<br><a href="about.php" title="About Us">About Us</a>
<br><a href="products.php" title="Shop!">Products</a>
<br><a href="cart.php" title="Your Cart">View Cart</a>
<br><a href="members.php" title="Members Only">Members</a>
<br><a href="logout.php" title="Log Out">Log Out</a>
</div>
</td><td>
And place the code for the end of a page into a file named footer.php
</td></tr>
<tr>
<td colspan="2">BOTTOM BAR (across page)</td>
</tr>
</table>
</body>
</html>
Now you can code each page more simply:
<?php
$title = "Main Content Area";
require("includes/header.php");
echo "<h2>$title</h2>\n";
?>
<p>This is the main content area.</p>
<p>Place HTML and PHP code between the header and footer.</p>
<?php
require("includes/footer.php");
?>
When you need to change the layout, all the code is in one place
Your whole site can change by modifying a single file
Later on we will look at better ways to organize the content of each page
^ top
7.4.5: Summary
- Starting with an organized web site will save time even in the short term
- You can make additions and changes with minimal problems
- You organize your application code into directories like this:
dbform.php
dbentry.php
includes/
dbconvars.php
header.php
footer.php
Place all files controlling the HTML document structure in your web-application root directory
Other files should be placed relative to your web-application root in subdirectories to reduce clutter
You should keep common code, both HTML and PHP, in included files
This practice allows you to reuse code from page to page
When you need to make changes, you only need to edit one or two files
^ top
Exercise 7.4
Use the next 10 minutes to complete the following.
- Label this exercise: Exercise 7.4.
- Complete the following exercises and answer any questions.
Specifications
Install and run the files of section 7.4.4.
- What is the purpose of the top bar area?
- What is the purpose of the side menu?
- What code do you need to change to remove the bottom bar?
^ top
Wrap Up
^ top
Home
| WebCT
| Announcements
| Course info
| Expectations
| Schedule
Project
| Help
| FAQ's
| HowTo's
| Links
Last Updated: March 23 2006 @14:53:56
|