Sei sulla pagina 1di 556

Chapter 1

Getting Started with PHP


2nd Edition

Objectives
In this chapter you will:
Create PHP scripts
Create PHP code blocks
Work with variables and constants
Study data types
Use expressions and operators

Creating Basic PHP Scripts


Embedded language refers to code that is
embedded within a Web page (XHTML document)
PHP code is typed directly into a Web page as
a separate section
A Web page containing PHP code must be saved
with an extension of .php to be processed by the
scripting engine
PHP code is never sent to a clients Web browser;
only the output of the processing is sent to the
browser
3

Creating Basic PHP Scripts


(continued)
The Web page generated from the PHP code,
and XHTML elements found within the PHP file,
is returned to the client
A PHP file that does not contain any PHP code
should be saved with an .html extension
.php is the default extension that most Web
servers use to process PHP scripts

Creating PHP Code Blocks


Code declaration blocks are separate sections
on a Web page that are interpreted by the
scripting engine
There are four types of code declaration blocks:

Standard PHP script delimiters


The <script> element
Short PHP script delimiters
ASP-style script delimiters

Standard PHP Script Delimiters


A delimiter is a character or sequence of
characters used to mark the beginning and end
of a code segment
The standard method of writing PHP code
declaration blocks is to use the <?php and ?>
script delimiters
The individual lines of code that make up a PHP
script are called statements

The <script> Element


The <script> element identifies a script
section in a Web page document
Assign a value of "php" to the language attribute
of the <script> element to identify the code
block as PHP

Short PHP Script Delimiters


The syntax for the short PHP script delimiters is
<? statements; ?>

Short delimiters can be disabled in a Web


servers php.ini configuration file
PHP scripts will not work if your Web site ISP
does not support short PHP script delimiters
Short delimiters can be used in XHTML
documents, but not in XML documents
8

ASP-Style Script Delimiters


The syntax for the ASP-style script delimiters is
<% statements; %>

ASP-style script delimiters can be used in


XHTML documents, but not in XML documents
ASP-style script delimiters can be enabled or
disabled in the php.ini configuration file
To enable or disable ASP-style script delimiters,
assign a value of On or Off to the asp_tags
directive in the php.ini configuration file
9

Understanding Functions
A function is a subroutine (or individual statements

grouped into a logical unit) that performs a specific task


To execute a function, you must invoke, or call, it
from somewhere in the script

A function call is the function name followed by


any data that the function needs
The data (in parentheses following the function
name) are called arguments or actual parameters
Sending data to a called function is called passing
arguments
10

Displaying Script Results


The echo and print statements are language
constructs (built-in features of a programming
language) that create new text on a Web page
that is returned as a response to a client
The text passed to the echo statement is called
a literal string and must be enclosed in either
single or double quotation marks
To pass multiple arguments to the echo
statement, separate the statements with commas
11

Displaying Script Results


(continued)
Use the echo and print statements to return
the results of a PHP script within a Web page
that is returned to a client
The print statement returns a value of 1 if
successful or a value of 0 if not successful, while
the echo statement does not return a value

12

Creating Multiple Code Declaration


Blocks
For multiple script sections in a document,
include a separate code declaration block for
each section
...
</head>
<body>
<h1>Multiple Script Sections</h1>
<h2>First Script Section</h2>
<?php echo "<p>Output from the first script section.</p>";
?>
<h2>Second Script Section</h2>
<?php echo "<p>Output from the second script
section.</p>";?>
</body>
</html>
13

Creating Multiple Code Declaration


Blocks (continued)
PHP code declaration blocks execute on a Web
server before a Web page is sent to a client
...
</head>
<body>
<h1>Multiple Script Sections</h1>
<h2>First Script Section</h2>
<p>Output from the first script section.</p>
<h2>Second Script Section</h2>
<p>Output from the second script section.</p>
</body>
</html>

14

Creating Multiple Code Declaration


Blocks (continued)

Figure 1-9 Output of a document with two PHP script sections


15

Creating Multiple Code Declaration


Blocks (continued)

Figure 1-10 PHP Environment Information Web page


16

Case Sensitivity in PHP


Programming language constructs in PHP are
mostly case insensitive
<?php
echo "<p>Explore <strong>Africa</strong>, <br />";
Echo "<strong>South America</strong>, <br />";
ECHO " and <strong>Australia</strong>!</p>";
?>

17

Adding Comments to a PHP Script


Comments are nonprinting lines placed in code
that do not get executed, but provide helpful
information, such as:

The name of the script


Your name and the date you created the program
Notes to yourself
Instructions to future programmers who might
need to modify your work

18

Adding Comments to a PHP Script


(continued)
Line comments hide a single line of code
Add // or # before the text

Block comments hide multiple lines of code


Add /* to the first line of code
And */ after the last character in the code

19

Adding Comments to a PHP Script


(continued)
<?php
/*
This line is part of the block comment.
This line is also part of the block comment.
*/
echo "<h1>Comments Example</h1>"; // Line comments can
follow
code statements
// This line comment takes up an entire line.
# This is another way of creating a line comment.
/* This is another way of creating
a block comment. */
?>

20

Using Variables and Constants


The values stored in computer memory are called
variables
The values, or data, contained in variables are
classified into categories known as data types
The name you assign to a variable is called an
identifier
An identifier must begin with a dollar sign ($), may
not include a number or underscore as the first
character, cannot include spaces, and is case
sensitive
21

Displaying Variables
To display a variable with the echo statement,
pass the variable name to the echo
statement without enclosing it in quotation marks:
$VotingAge = 18;
echo $VotingAge;

To display both text strings and variables, send


them to the echo statement as individual
arguments, separated by commas:
echo "<p>The legal voting age is ",
$VotingAge, ".</p>";
22

Naming Variables
The name you assign to a variable is called an identifier
The following rules and conventions must be followed
when naming a variable:
Identifiers must begin with a dollar sign ($)
Identifiers may contain uppercase and lowercase letters,
numbers, or underscores (_). The first character after the
dollar sign must be a letter.
Identifiers cannot contain spaces
Identifiers are case sensitive

23

Declaring and Initializing Variables


Specifying and creating a variable name is
called declaring the variable
Assigning a first value to a variable is called
initializing the variable
In PHP, you must declare and initialize a variable
in the same statement:
$variable_name = value;

24

Displaying Variables

Figure 1-11 Output from an echo statement


that is passed text and a variable

25

Displaying Variables (continued)


The output of variable names inside a text string
depends on whether the string is surrounded by
double or single quotation marks

Figure 1-12 Output of an echo statement that includes text and a


variable surrounded by single quotation marks
26

Modifying Variables
You can modify a variables value at any point in a
script
$SalesTotal = 40;
echo "<p>Your sales total is
$$SalesTotal</p>";
$SalesTotal = 50;
echo "<p>Your new sales total is
$SalesTotal</p>";

27

Defining Constants
A constant contains information that does not
change during the course of program execution
Constant names do not begin with a dollar sign
($)
Constant names use all uppercase letters
Use the define() function to create a constant
define("CONSTANT_NAME", value);

The value you pass to the define() function


can be a text string, number, or Boolean value
28

Working with Data Types


A data type is the specific category of
information that a variable contains
Data types that can be assigned only a single
value are called primitive types

29

Working with Data Types


(continued)
The PHP language supports:
A resource data type a special variable that
holds a reference to an external resource such
as a database or XML file
Reference or composite data types, which
contain multiple values or complex types of
information
Two reference data types: arrays and objects

30

Working with Data Types


(continued)
Strongly typed programming languages
require you to declare the data types of variables
Static or strong typing refers to data types that
do not change after they have been declared
Loosely typed programming languages do
not require you to declare the data types of
variables
Dynamic or loose typing refers to data types
that can change after they have been declared
31

Numeric Data Types


PHP supports two numeric data types:
An integer is a positive or negative number and 0
with no decimal places (-250, 2, 100, 10,000)
A floating-point number is a number that
contains decimal places or that is written in
exponential notation (-6.16, 3.17, 2.7541)
Exponential notation, or scientific notation, is a
shortened format for writing very large numbers or
numbers with many decimal places (2.0e11)

32

Boolean Values
A Boolean value is a value of TRUE or FALSE
It decides which part of a program should
execute and which part should compare data
In PHP programming, you can only use TRUE or
FALSE Boolean values
In other programming languages, you can use
integers such as 1 = TRUE, 0 = FALSE

33

Arrays
An array contains a set of data represented by a
single variable name

Figure 1-17 Conceptual example of an array


34

Declaring and Initializing Indexed


Arrays
An element refers to each piece of data that is
stored within an array
An index is an elements numeric position within
the array
By default, indexes begin with the number zero
(0)
An element is referenced by enclosing its index in
brackets at the end of the array name:
$Provinces[1]

35

Declaring and Initializing Indexed


Arrays (continued)
The array() construct syntax is:
$array_name = array(values);
$Provinces = array(
"Newfoundland and Labrador",
"Prince Edward Island",
"Nova Scotia",
"New Brunswick",
"Quebec",
"Ontario",
"Manitoba",
"Saskatchewan",
"Alberta",
"British Columbia"
);
36

Declaring and Initializing Indexed


Arrays (continued)
Array name and brackets syntax is:
$array_name[ ]
$Provinces[]
$Provinces[]
$Provinces[]
$Provinces[]
$Provinces[]
$Provinces[]
$Provinces[]
$Provinces[]
$Provinces[]
$Provinces[]

=
=
=
=
=
=
=
=
=
=

"Newfoundland and Labrador";


"Prince Edward Island";
"Nova Scotia";
"New Brunswick";
"Quebec";
"Ontario";
"Manitoba";
"Saskatchewan";
"Alberta";
"British Columbia";
37

Accessing Element Information


(continued)
echo "<p>Canada's smallest province is
$Provinces[1].<br />";
echo "Canada's largest province is
$Provinces[4].</p>";

Figure 1-18 Output of elements in the $Provinces[] array


38

Accessing Element Information


(continued)
Use the count() function to find the total
number of elements in an array
$Provinces = array("Newfoundland and Labrador", "Prince
Edward
Island", "Nova Scotia", "New Brunswick", "Quebec",
"Ontario", " Manitoba", "Saskatchewan", "Alberta", "British
Columbia");
$Territories = array("Nunavut", "Northwest Territories",
"Yukon
Territory");
echo "<p>Canada has ", count($Provinces), " provinces and ",
count($Territories), " territories.</p>";
39

Accessing Element Information


(continued)

Figure 1-19 Output of the count() function

40

Accessing Element Information


(continued)
Use the print_r(), var_dump() or
var_export() functions to display or return
information about variables
The print_r() function displays the index and value

of each element in an array


The var_dump() function displays the index, value,
data type and number of characters in the value
The var_export() function is similar to
var_dump() function except it returns valid PHP code

41

Accessing Element Information


(continued)

Figure 1-21 Output of the $Provinces[ ] array with the


print_r() function
42

Modifying Elements
To modify an array element. include the index for
an individual element of the array:
$HospitalDepts = array(
"Anesthesia",
"Molecular Biology",
"Neurology");

// first element(0)
// second element (1)
// third element (2)

To change the first array element in the


$HospitalDepts[] array from Anesthesia to
Anesthesiology use:
$HospitalDepts[0] = "Anesthesiology";
43

Avoiding Assignment Notation


Pitfalls
Assigns the string Hello to a variable named
$list
$list = "Hello";
Assigns the string Hello to a new element
appended to the end of the $list array
$list[] = "Hello";
Replaces the value stored in the first element
(index 0) of the $list array with the string Hello
$list[0] = "Hello";
44

Building Expressions
An expression is a literal value or variable that
can be evaluated by the PHP scripting engine to
produce a result
Operands are variables and literals contained in
an expression
A literal is a static value such as a literal string
or a number
Operators are symbols (+) (*) that are used in
expressions to manipulate operands
45

Building Expressions (continued)

46

Building Expressions (continued)


A binary operator requires an operand before
and after the operator
$MyNumber = 100;

A unary operator requires a single operand


either before or after the operator

47

Arithmetic Operators
Arithmetic operators are used in PHP to
perform mathematical calculations (+ - x )

48

Arithmetic Operators (continued)

Figure 1-22 Results of arithmetic expressions


49

Arithmetic Operators (continued)


$DivisionResult = 15 / 6;
$ModulusResult = 15 % 6;
echo "<p>15 divided by 6 is
$DivisionResult.</p>"; // prints '2.5'
echo "The whole number 6 goes into 15 twice, with a
remainder of $ModulusResult.</p>"; // prints '3'

Figure 1-23 Division and modulus expressions


50

Arithmetic Binary Operators

51

Arithmetic Unary Operators


The increment (++) and decrement (--) unary
operators can be used as prefix or postfix
operators
A prefix operator is placed before a variable
A postfix operator is placed after a variable

52

Arithmetic Unary Operators (continued)

Figure 1-24 Script that uses the prefix


increment operator

53

Arithmetic Unary Operators (continued)


Figure 1-25 Output of the prefix version of the student ID script

54

Arithmetic Unary Operators (continued)

Figure 1-26 Script that uses the postfix increment operator


55

Arithmetic Unary Operators (continued)

Figure 1-27 Output of the postfix version of the student ID script

56

Assignment Operators
Assignment operators are used for assigning
a value to a variable:
$MyFavoriteSuperHero = "Superman";
$MyFavoriteSuperHero = "Batman";

Compound assignment operators perform


mathematical calculations on variables and
literal values in an expression, and then assign
a new value to the left operand

57

Assignment Operators (continued)

58

Comparison and Conditional


Operators
Comparison operators are used to compare two
operands and determine how one operand
compares to another
A Boolean value of TRUE or FALSE is returned after
two operands are compared
The comparison operator compares values,
whereas the assignment operator assigns values
Comparison operators are used with conditional
statements and looping statements
59

Comparison and Conditional


Operators (continued)

60

Comparison and Conditional


Operators (continued)
The conditional operator executes one of two
expressions, based on the results of a
conditional expression
The syntax for the conditional operator is:
conditional expression ? expression1 :
expression2;

If the conditional expression evaluates to TRUE,


expression1 executes
If the conditional expression evaluates to FALSE,
expression2 executes
61

Comparison and Conditional


Operators (continued)
$BlackjackPlayer1 = 20;
($BlackjackPlayer1 <= 21) ? $Result =
"Player 1 is still in the game. " : $Result =
"Player 1 is out of the action.";
echo "<p>", $Result, "</p>";

Figure 1-31 Output of a script with a conditional operator


62

Logical Operators
Logical operators are used for comparing two
Boolean operands for equality
A Boolean value of TRUE or FALSE is returned
after two operands are compared

63

Special Operators

64

Type Casting
Casting or type casting copies the value
contained in a variable of one data type into a
variable of another data type
The PHP syntax for casting variables is:
$NewVariable = (new_type) $OldVariable;

(new_type) refers to the type-casting operator


representing the type to which you want to cast
the variable

65

Type Casting (continued)


Returns one of the following strings, depending
on the data type:

Boolean
Integer
Double
String
Array
Object
Resource
NULL
Unknown type
66

Understanding Operator
Precedence
Operator precedence refers to the order in
which operations in an expression are evaluated
Associativity is the order in which operators of
equal precedence execute
Associativity is evaluated on a left-to-right or a
right-to-left basis

67

Understanding Operator
Precedence (continued)

68

Summary
JavaScript and PHP are both referred to as
embedded languages because code for both
languages is embedded within a Web page
(either an HTML or XHTML document)
You write PHP scripts within code declaration
blocks, which are separate sections within a
Web page that are interpreted by the scripting
engine
The individual lines of code that make up a PHP
script are called statements
69

Summary (continued)
The term, function, refers to a procedure (or
individual statements grouped into a logical unit)
that performs a specific task
Comments are lines that you place in code to
contain various types of remarks, including the
name of the script, your name and the date you
created the program, notes to yourself, or
instructions to future programmers who might
need to modify your work
Comments do not display in the browser
70

Summary (continued)
The values a program stores in computer
memory are commonly called variables
The name you assign to a variable is called an
identifier
A constant contains information that cannot
change during the course of program execution
A data type is the specific category of
information that a variable contains
PHP is a loosely-typed programming language
71

Summary (continued)
An integer is a positive or negative number or
zero, with no decimal places
A floating-point number contains decimal places
or is written in exponential notation
A Boolean value is a logical value of TRUE or
FALSE
An array contains a set of data represented by a
single variable name

72

Summary (continued)
An expression is a single literal value or
variable or a combination of literal values,
variables, operators, and other expressions that
can be evaluated by the PHP scripting engine to
produce a result
Operands are variables and literals contained in
an expression. A literal is a value such as a
string or a number.

73

Summary (continued)
Operators are symbols used in expressions to
manipulate operands, such as the addition
operator (+) and multiplication operator (*)
A binary operator requires an operand before
and after the operator
A unary operator requires a single operand
either before or after the operator

74

Summary (continued)
Arithmetic operators are used in the PHP
scripting engine to perform mathematical
calculations, such as addition, subtraction,
multiplication, and division
Assignment operators are used for assigning a
value to a variable
Comparison operators are used to determine
how one operand compares with another

75

Summary (continued)
The conditional operator executes one of two
expressions, based on the results of a
conditional expression
Logical operators are used to perform
operations on Boolean operands
Casting or type casting creates an equivalent
value in a specific data type for a given value
Operator precedence is the order in which
operations in an expression are evaluated
76

Chapter 2
Functions and Control
Structures
2nd Edition

Objectives
In this chapter, you will:
Study how to use functions to organize your PHP
code
Learn about variable scope
Make decisions using if statements, if...else
statements, and switch statements
Repeatedly execute while statements,
do...while statements, for, and foreach
statements
Learn about include and require statements
78

Defining Functions
Functions are groups of statements that you
can execute as a single unit
Function definitions are the lines of code that
make up a function
The syntax for defining a function is :
<?php
function name_of_function(parameters) {
statements;
}
?>
79

Defining Functions (continued)


Functions, like all PHP code, must be contained
within <?php ... ?> tags
A parameter is a variable that is passed to a
function when it is called
Parameters are placed within the parentheses
that follow the function name
Functions do not have to contain parameters
The set of curly braces (called function braces)
contain the function statements
80

Defining Functions (continued)


Function statements do the actual work of
the function and must be contained within the
function braces
function displayCompanyName($Company1,
$Company2, $Company3) {
echo "<p>$Company1</p>";
echo "<p>$Company2</p>";
echo "<p>$Company3</p>";
}
81

Calling Functions
function displayCompanyName($CompanyName) {
echo "<p>$CompanyName</p>";
}
displayCompanyName("Course Technology");

Figure 2-1 Output of a call to a custom function


82

Returning Values
A return statement returns a value to the
statement that called the function
Not all functions return values
function averageNumbers($a, $b, $c) {
$SumOfNumbers = $a + $b + $c;
$Result = $SumOfNumbers / 3;
return $Result;
}

83

Returning Values (continued)


You can pass a function parameter by value or
by reference
A function parameter that is passed by value is a
local copy of the variable.
A function parameter that is passed by reference
is a reference to the original variable.

84

Understanding Variable Scope


Variable scope is where in your program a
declared variable can be used
A variables scope can be either global or local
A global variable is one that is declared outside
a function and is available to all parts of your
program
A local variable is declared inside a function
and is only available within the function in which
it is declared
85

The global Keyword


In PHP, you must declare a global variable with
the global keyword inside a function definition
to make the variable available within the scope
of that function

86

The global Keyword


(continued)
<?php
$GlobalVariable = "Global variable";
function scopeExample() {
global $GlobalVariable;
echo "<p>$GlobalVariable</p>";
}
scopeExample();
?>

87

Making Decisions
Decision making or flow control is the process
of determining the order in which statements
execute in a program
The special types of PHP statements used for
making decisions are called decision-making
statements or decision-making structures

88

if Statements
Used to execute specific programming code if
the evaluation of a conditional expression
returns a value of TRUE
The syntax for a simple if statement is:
if (conditional expression)
statement;

89

if Statements (continued)
Contains three parts:
the keyword if
a conditional expression enclosed within
parentheses
the executable statements

A command block is a group of statements


contained within a set of braces
Each command block must have an opening
brace ( { ) and a closing brace ( } )
90

if Statements (continued)
$ExampleVar = 5;
if ($ExampleVar == 5) {
// condition evaluates to 'TRUE'
echo " <p>The condition evaluates to true.</p> ";
echo '<p>$ExampleVar is equal to ',
" $ExampleVar.</p> ";
echo " <p>Each of these lines will be printed.</p> ";
}
echo " <p>This statement always executes after the if
statement.</p> ";

91

if...else Statements
An if statement that includes an else clause is
called an if...else statement
An else clause executes when the condition in
an if...else statement evaluates to FALSE
The syntax for an if...else statement is:
if (conditional expression)
statement;
else
statement;
92

if...else Statements
(continued)
An if statement can be constructed without the
else clause
The else clause can only be used with an if
statement
$Today = " Tuesday ";
if ($Today == " Monday ")
echo " <p>Today is Monday</p> ";
else
echo " <p>Today is not Monday</p> ";

93

Nested if and if...else


Statements
When one decision-making statement is
contained within another decision-making
statement, they are referred to as nested
decision-making structures
if ($SalesTotal >= 50)
if ($SalesTotal <= 100)
echo " <p>The sales total is between
50 and 100, inclusive.</p> ";

94

switch Statements
Control program flow by executing a specific set
of statements depending on the value of an
expression
Compare the value of an expression to a value
contained within a special statement called a
case label
A case label is a specific value that contains
one or more statements that execute if the value
of the case label matches the value of the switch
statements expression
95

switch Statements (continued)


Consist of the following components:

The switch keyword


An expression
An opening brace
One or more case labels
The executable statements
The break keyword
A default label
A closing brace
96

switch Statements (continued)


The syntax for the switch statement is:
switch (expression) {
case label:
statement(s);
break;
case label:
statement(s);
break;
...
default:
statement(s);
break;
}
97

switch Statements (continued)


A case label consists of:
The keyword case
A literal value or variable name
A colon (:)

A case label can be followed by a single


statement or multiple statements
Multiple statements for a case label do not need
to be enclosed within a command block
98

switch Statements (continued)


The default label contains statements that
execute when the value returned by the switch
statement expression does not match a case
label
A default label consists of the keyword
default followed by a colon (:)

99

Repeating Code
A loop statement is a control structure that
repeatedly executes a statement or a series of
statements while a specific condition is TRUE or
until a specific condition becomes TRUE
There are four types of loop statements:
while statements
do...while statements
for statements
foreach statements
100

while Statements
Tests the condition prior to executing the series
of statements at each iteration of the loop
The syntax for the while statement is:
while (conditional expression) {
statement(s);
}

As long as the conditional expression evaluates


to TRUE, the statement or command block that
follows executes repeatedly
101

while Statements (continued)


Each repetition of a looping statement is called
an iteration
A while statement keeps repeating until its
conditional expression evaluates to FALSE
A counter is a variable that increments or
decrements with each iteration of a loop
statement

102

while Statements (continued)


$Count = 1;
while ($Count <= 5) {
echo " $Count<br /> ";
++$Count;
}
echo " <p>You have printed 5 numbers.</p> ";

Figure 2-5 Output of a while statement using an increment operator


103

while Statements (continued)


$Count = 10;
while ($Count > 0) {
echo $Count<br />;
--$Count;
}
echo " <p>We have liftoff.
</p> ";

Figure 2-6 Output of a while statement using a decrement operator


104

while Statements (continued)


$Count = 1;
while ($Count <= 100) {
echo " $Count<br /> ";
$Count *= 2;
}

Figure 2-7 Output of a while statement using the assignment operator *=


105

while Statements (continued)


In an infinite loop, a loop statement never ends
because its conditional expression is never
FALSE
$Count = 1;
while ($Count <= 10) {
echo " The number is $Count ";
}

106

do...while Statements
Test the condition after executing a series of
statements then repeats the execution as long
as a given conditional expression evaluates to
TRUE
The syntax for the do...while statement is:
do {
statement(s);
} while (conditional expression);

107

do...while Statements
(continued)
do...while statements always execute once,
before a conditional expression is evaluated
$Count = 2;
do {
echo " <p>The count is equal to $Count</p> ";
++$Count;
} while ($Count < 2);

108

do...while Statements
(continued)
$DaysOfWeek = array(" Monday ", " Tuesday ", " Wednesday ", " Thursday ",
" Friday ", " Saturday ", " Sunday ");
$Count = 0;
do {
echo $DaysOfWeek[$Count], "<br />";
++$Count;
} while ($Count < 7);

Figure 2-9 Output of days of week script in Web browser


109

for Statements
Combine the initialize, conditional evaluation,
and update portions of a loop into a single
statement
Repeat a statement or a series of statements as
long as a given conditional expression evaluates
to TRUE
If the conditional expression evaluates to TRUE,
the for statement executes and continues to
execute repeatedly until the conditional
expression evaluates to FALSE
110

for Statements (continued)


Can also include code that initializes a counter
and changes its value with each iteration
The syntax of the for statement is:
for (counter declaration and initialization;
condition;
update statement) {
statement(s);
}

111

for Statements (continued)


$FastFoods = array(" pizza, " burgers ", " french fries ", " tacos
", " fried chicken ");
for ($Count = 0; $Count < 5; ++$Count) {
echo $FastFoods[$Count], " <br /> ";
}

Figure 2-10 Output of fast foods script


112

foreach Statements
Used to iterate or loop through the elements in
an array
Do not require a counter; instead, you specify an
array expression within a set of parentheses
following the foreach keyword
The syntax for the foreach statement is:
foreach ($array_name as $variable_name) {
statements;
}
113

foreach Statements
(continued)
$DaysOfWeek = array(("Monday", "Tuesday",
"Wednesday", "Thursday", "Friday",
"Saturday", "Sunday");
foreach ($DaysOfWeek as $Day) {
echo "<p>$Day</p>";
}

114

foreach Statements
(continued)
$DaysofWeek = array("Monday", "Tuesday",
"Wednesday", "Thursday", "Friday", "Saturday",
"Sunday");
foreach ($DaysOfWeek as $DayNumber => $Day) {
echo "<p>Day $DayNumber is $Day</p>";
}

Figure 2-11 Output of the foreach script with index values


115

Including Files
The include and require statements reuse
content by allowing you to insert the content of
an external file on multiple Web pages
The include statement generates a warning if
the include file cannot be found
The require statement halts the processing of
the Web page and displays an error if the include
file cannot be found

The include_once and require_once


statements assure that the external file is added
to the script only one time
116

Summary
The lines that make up a function are called the
function definition
A function parameter that is passed by value is
a local copy of the variable
A function parameter that is passed by
reference is a reference to the original variable
A global variable is declared outside a function
and is available to all parts of your program

117

Summary (continued)
A local variable is declared inside a function
and is only available within the function in which
it is declared
The process of determining the order in which
statements execute in a program is called
decision making or flow control
The if statement is used to execute specific
programming code if the evaluation of a
conditional expression returns a value of TRUE
118

Summary (continued)
An if statement that includes an else clause is
called an if...else statement. An else
clause executes when the condition in an
if...else statement evaluates to FALSE
When one decision-making statement is
contained within another decision-making
statement, they are referred to as nested
decision-making structures

119

Summary (continued)
The switch statement controls program flow by
executing a specific set of statements,
depending on the value of an expression
A loop statement is a control structure that
repeatedly executes a statement or a series of
statements while a specific condition is TRUE or
until a specific condition becomes TRUE
A while statement tests the condition prior to
executing the series of statements at each
iteration of the loop
120

Summary (continued)
The do...while statement tests the condition
after executing a series of statements
The for statement combines the initialize,
conditional evaluation, and update portions of a
loop into a single statement
The foreach statement is used to iterate or
loop through the elements in an array

121

Summary (continued)
The include, require, include_once, and
require_once statements insert the contents
of an external file at the location of the statement

122

Chapter 3
Manipulating Strings
2nd Edition

Objectives
In this chapter, you will:
Construct text strings
Work with single strings
Work with multiple strings and parse strings
Compare strings
Use regular expressions

124

Constructing Text Strings


A text string contains zero or more characters
surrounded by double or single quotation marks
Text strings can be used as literal values or
assigned to a variable
echo "<PHP literal text string</p>";
$StringVariable = "<p>PHP literal text
string</p>";
echo $StringVariable;

A string must begin and end with a matching


quotation mark (single or double)
125

Constructing Text Strings


(continued)
To include a quoted string within a literal string
surrounded by double quotation marks, you
surround the quoted string with single quotation
marks
To include a quoted string within a literal string
surrounded by single quotation marks, you
surround the quoted string with double quotation
marks

126

Constructing Text Strings


(continued)
$LatinQuote = '<p>"Et tu, Brute!"</p>';
echo $LatinQuote;

Figure 3-2 Output of a text string containing double quotation marks

127

Working with String Operators


In PHP, you use two operators to combine strings:
Concatenation operator (.) combines two
strings and assigns the new value to a variable
$City = "Paris";
$Country = "France";
$Destination = <p> . $City . " is in "
. $Country . ".</p>";
echo $Destination;

128

Working with String Operators


(continued)
You can also combine strings using the
concatenation assignment operator (.=)
$Destination = "<p>Paris";
$Destination .= "is in France.</p>";
echo $Destination;

129

Adding Escape Characters and


Sequences
An escape character tells the compiler or
interpreter that the character that follows it has a
special purpose
In PHP, the escape character is the backslash (\)
echo '<p>This code\'s going to work</p>';

Do not add a backslash before an apostrophe


if you surround the text string with double
quotation marks
echo "<p>This code's going to work.</p>";
130

Adding Escape Characters and


Sequences (continued)
The escape character combined with one or
more other characters is an escape sequence

131

Adding Escape Characters and


Sequences (continued)
$Speaker = "Julius Caesar";
echo "<p>\"Et tu, Brute!\" exclaimed
$Speaker.</p>";

Figure 3-4 Output of literal text containing double quotation escape sequences

132

Simple and Complex String


Syntax
Simple string syntax uses the value of a
variable within a string by including the variable
name inside a text string with double quotation
marks
$Vegetable = "broccoli";
echo "<p>Do you have any $Vegetable?</p>";

When variables are placed within curly braces


inside of a string, it is called complex string
syntax
$Vegetable = "carrot";
echo "<p>Do you have any {$Vegetable}s?</p>";
133

Working with a Single String


PHP provides a number of functions for
analyzing, altering, and parsing text strings
including:
Counting characters and words
Transposing, converting, and changing the case
of text within a string

134

Counting Characters and Words

in
a
String
The most commonly used string counting

function is the strlen() function, which returns


the total number of characters in a string
Escape sequences, such as \n, are counted as
one character
$BookTitle = "The Cask of Amontillado";
echo "<p>The book title contains " .
strlen($BookTitle) . " characters.</p>";

135

Counting Characters and Words

in
a
String
(continued)
The str_word_count() function returns the

number of words in a string


Pass the str_word_count() function a literal
string or the name of a string variable whose
words you want to count
$BookTitle = "The Cask of Amontillado";
echo "<p>The book title contains " .
str_word_count($BookTitle). " words.</p>";

136

Modifying the Case of a String


PHP provides several functions to manipulate
the case of a string
The strtoupper()function converts all letters
in a string to uppercase
The strtolower()function converts all letters
in a string to lowercase
The ucfirst()function ensures that the first
character of a word is uppercase
The lcfirst()function ensures that the first
character of a word is lowercase
137

Modifying the Case of a String


(continued)
Functions to manipulate the case of a string:
The ucwords()function changes the first
character of each word
Use the strtolower()function on a string
before using the ucfirst()and ucwords() to

ensure that the remaining characters in a string are


in lowercase
Use the strtoupper()function on a string
before using the ucfirst() and ucwords() to
ensure that the remaining characters in a string are
in uppercase
138

Encoding and Decoding a String


PHP has several built-in functions to use with
Web pages:
Some characters in XHTML have a special
meaning and must be encoded using HTML
entities in order to preserve that meaning
The htmlspecialchars()function converts
special characters to HTML entities
The html_specialcharacters_decode()
function converts HTML character entities into
their equivalent characters
139

Encoding and Decoding a String


(continued)
The characters that are converted with the
htmlspecialchars()function are:
'&' (ampersand) becomes '&amp;'
'"' (double quote) becomes '&quot;' when
ENT_NOQUOTES is disabled.
''' (single quote) becomes '&#039;' only when
ENT_QUOTES is enabled.
'<' (less than) becomes '&lt;'
'>' (greater than) becomes '&gt;'
140

Encoding and Decoding a String


(continued)
If ENT_QUOTES is enabled in the PHP
configuration, both single and double quotes are
converted
If ENT_QUOTES is disabled in the PHP
configuration, neither single nor double quotes
are converted

141

Encoding and Decoding a String


(continued)
The md5()function uses a strong encryption
algorithm (called the Message-Digest
Algorithm) to create a one-way hash
A one-way hash is a fixed-length string based
on the entered text, from which it is nearly
impossible to determine the original text
The md5() function does not have an
equivalent decode function, which makes it a
useful function for storing passwords in a
database
142

Other Ways to Manipulate a


String
PHP provides three functions that remove
leading or trailing spaces in a string
The trim()function will strip (remove) leading or
trailing spaces in a string
The ltrim() function removes only the leading
spaces
The rtrim() function removes only the trailing
spaces
143

Other Ways to Manipulate a


String (continued)
The substr()function returns part of a string based
on the values of the start and length parameters
The syntax for the substr() function is:
substr(string, start, optional length);

A positive number in the start parameter indicates


how many character to skip at the beginning of the
string
A negative number in the start parameter indicates
how many characters to count in from the end of the
string
144

Other Ways to Manipulate a


String
(continued)
A positive value in the in the length parameter

determines how many characters to return


A negative value in the length parameter skip
that many characters at the end of the string and
returns the middle portion
If the length is omitted or is greater than the
remaining length of the string, the entire
remainder of the string is returned

145

Other Ways to Manipulate a


String
(continued)
$ExampleString = "woodworking project";
echo
echo
echo
echo
echo

substr($ExampleString,4) . "<br />\n";


substr($ExampleString,4,7) . "<br />\n";
substr($ExampleString,0,8) . "<br />\n";
substr($ExampleString,-7) . "<br />\n";
substr($ExampleString,-12,4) . "<br />\n";

Figure 3-10 Some examples using the substr() function


146

Working with Multiple Strings


Parsing is the act of dividing a string into logical
component substrings or tokens
When programming, parsing refers to the
extraction of information from string literals
and variables

147

Finding and Extracting


Characters and Substrings
There are two types of string search and
extraction functions:
Functions that return a numeric position in a
text string
Functions that return a character or substring
Both functions return a value of FALSE if
the search string is not found

148

Finding and Extracting


Characters and Substrings
(continued)
The strpos() function performs a case-

sensitive search and returns the position of the


first occurrence of one string in another string
Pass two arguments to the strpos() function:
The first argument is the string you want to search
The second argument contains the characters for
which you want to search

If the search string is not found, the strpos()


function returns a Boolean value of FALSE
149

Finding and Extracting


Characters and Substrings
(continued)
Pass to the strchr() and the strrchr()

functions the string and the character for which


you want to search
Both functions return a substring from the
specified characters to the end of the string
strchr() function starts searching at the
beginning of a string
strrchr() function starts searching at the
end of a string
150

Replacing Characters and


Substrings
The str_replace() and str_ireplace()
functions both accept three arguments:
The string you want to search for
A replacement string
The string in which you want to replace characters
$Email = "president@whitehouse.gov";
$NewEmail = str_replace("president", "vice.president", $Email);
echo $NewEmail; // prints 'vice.president@whitehouse.gov'

151

Dividing Strings into Smaller


Pieces
Use the strtok() function to break a string
into smaller strings, called tokens
The syntax for the strtok() function is:
$variable = strtok(string, separators);

The strtok() function returns the entire string


if:
An empty string is specified as the second argument
of the strtok() function
The string does not contain any of the separators
specified
152

Dividing Strings into Smaller


Pieces (continued)

$Presidents = " George Washington;John Thomas Jefferson;James


Madison;James Monroe";
$President = strtok($Presidents, ";");
while ($President != NULL) {
echo "$President<br />";
$President = strtok(";");
}

Figure 3-15 Output of a script that uses the strtok() function


153

Dividing Strings into Smaller


Pieces(continued)
$Presidents = " George Washington;John Adams;Thomas
Jefferson;James Madison;James Monroe";
$President = strtok($Presidents, "; ");
while ($President != NULL) {
echo "$President<br />";
$President = strtok("; ");
}

Figure 3-16 Output of a script


with a strtok() function
that uses two separators

154

Converting between Strings and


Arrays
The str_split() and explode() functions
split a string into an indexed array
The str_split() function splits each
character in a string into an array element using
the syntax:
$array = str_split(string[, length]);

The length argument represents the number


of characters you want assigned to each array
element
155

Converting between Strings and


Arrays (continued)
The explode() function splits a string into an
indexed array at a specified separator
The syntax for the explode() function is:
$array = explode(separators, string);

The order of the arguments for the explode()


function is the reverse of the arguments for the
strtok() function

156

Converting between Strings and


Arrays (continued)
$Presidents = "George Washington;JohnAdams;
Thomas Jefferson;James Madison;James Monroe";
$PresidentArray = explode(";", $Presidents);
foreach ($PresidentArray as $President) {
echo "$President<br />";
}

If the string does not contain the specified


separators, the entire string is assigned to the
first element of the array

157

Converting between Strings and


Arrays (continued)
The explode() function
Does not separate a string at each character that
is included in the separator argument
Evaluates the characters in the separator
argument as a substring
If you pass to the explode()function an empty
string as the separator argument, the function
returns a Boolean value of FALSE

158

Converting between Strings and


Arrays (continued)
The implode()function combines an arrays
elements into a single string, separated by
specified characters
The syntax is:
$variable = implode(separators, array);

159

Converting between Strings and


Arrays (continued)
$PresidentsArray = array("George Washington", John Adams",
Thomas Jefferson", James Madison", James Monroe");
$Presidents = implode(", ", $PresidentsArray);
echo $Presidents;

Figure 3-18 Output of a string created with the implode() function


160

Comparing Strings
Comparison operators compare individual characters
by their position in the American Standard Code for
Information Interchange (ASCII), which are
numeric representations of English characters
$FirstLetter = "A";
$SecondLetter = "B";
if ($SecondLetter > $FirstLetter)
echo "<p>The second letter is higher in the alphabet
than the first letter.</p>";
else
echo "<p>The second letter is lower in the alphabet than
The first letter.</p>";

161

Comparing Strings (continued)


American Standard Code for Information
Interchange (ASCII) values range from 0 to 255
Lowercase letters are represented by the values
97 (a) to 122 (z)
Uppercase letters are represented by the values
65 (A) to 90 (Z)

162

String Comparison Functions


The strcasecmp() function performs a caseinsensitive comparison of strings
The strcmp() function performs a casesensitive comparison of strings
Both functions accept two arguments
representing the strings you want to compare
Most string comparison functions compare
strings based on their ASCII values

163

Determining the Similarity of


Two Strings
The similar_text() and levenshtein()
functions are used to determine the similarity
between two strings
The similar_text() function returns the
number of characters that two strings have in
common
The levenshtein() function returns the
number of characters you need to change for
two strings to be the same

164

Determining the Similarity of


Two Strings (continued)
Both functions accept two string arguments
representing the values you want to compare
$FirstName = "Don";
$SecondName = "Dan";
echo "<p>The names \"$FirstName\ and \"$SecondName\ have .
similar_text($FirstName, $SecondName) . characters in
common.</p>";
echo "<p>You must change . levenshtein($FirstName, $SecondName)
. character(s) to make the names \"$FirstName\ and
\"$SecondName\ the same.</p>";

165

Determining the Similarity of


Two Strings (continued)

Figure 3-20 Output of a script with the similar_text()


and levenshtein() functions

166

Determining if Words are


Pronounced Similarly
The soundex() and metaphone() functions
determine whether two strings are pronounced
similarly
Both functions return a value representing how
words sound
The soundex() function returns a value
representing a names phonetic equivalent
The metaphone() function returns a code
representing an English words approximate
sound
167

Determining if Words are


Pronounced Similarly
(continued)
$FirstName = "Gosselin";
$SecondName = "Gauselin";
$FirstNameSoundsLike = metaphone($FirstName);
$SecondNameSoundsLike = metaphone($SecondName);
if ($FirstNameSoundsLike == $SecondNameSoundsLike)
echo "<p>The names are pronounced the same.</p>";
else
echo "<p>The names are not pronounced the same.</p>";

168

Working with Regular


Expressions
Regular Expressions are patterns that are used
for matching and manipulating strings according
to specified rules
PHP supports two types of regular expressions:
POSIX Extended
Perl Compatible Regular Expressions

169

Working with Regular


Expressions
(continued)

170

Working with Regular


Expressions
(continued)
Pass to the preg_match() the regular

expression pattern as the first argument and a


string containing the text you want to search as
the second argument
preg_match(pattern, string);

171

Writing Regular Expression


Patterns
A regular expression pattern is a special text
string that describes a search pattern
Regular expression patterns consist of literal
characters and metacharacters, which are
special characters that define the patternmatching rules
Regular expression patterns are enclosed in
opening and closing delimiters
The most common character delimiter is the
forward slash (/)
172

Writing Regular Expression


Patterns
(continued)

173

Matching Any Character


A period (.) in a regular expression pattern specifies

that the pattern must contain a value at the location


of the period
A return value of 0 indicates that the string does not
match the pattern and 1 if it does
$ZIP = "015";

preg_match("/...../", $ZIP); // returns 0


$ZIP = "01562";
preg_match("/...../", $ZIP); // returns 1
174

Matching Characters at the


Beginning or End of a String
An anchor specifies that the pattern must appear
at a particular position in a string
The ^ metacharacter anchors characters to the
beginning of a string
The $ metacharacter anchors characters to the
end of a string
$URL = "http://www.dongosselin.com";
preg_match("/^http/", $URL); // returns 1

175

Matching Characters at the Beginning


or End of a String (continued)
To specify an anchor at the beginning of a string,
the pattern must begin with a ^ metcharacter
$URL = "http://www.dongosselin.com";
eregi("^http", $URL); // returns 1;

To specify an anchor at the end of a line, the


pattern must end with the $ metacharacter
$Identifier = "http://www.dongosselin.com";
eregi("com$", $Identifier); // returns 1

176

Matching Special Characters


To match any metacharacters as literal values in
a regular expression, escape the character with a
backslash
(in the following example, the last four characters in the
string must be .com)
$Identifier = http://www.dongosselin.com";
preg_match("/gov$/", $Identifier);//returns 0

177

Specifying Quantity
Metacharacters that specify the quantity of a
match are called quantifiers

178

Specifying Quantity
(continued)
A question mark (?) quantifier specifies that the
preceding character in the pattern is optional
(in the following example, the string must begin with http
or https)
$URL = "http://www.dongosselin.com";
preg_match("/^https?/", $URL); // returns 1

179

Specifying Quantity
(continued)
The addition(+) quantifier specifies that one or
more sequential occurrences of the preceding
characters match
(in the following example, the string must have at least
one character)
$Name = "Don";
preg_match("/.+/", $Name); // returns 1

180

Specifying Quantity
(continued)
A asterisk (*) quantifier specifies that zero or
more sequential occurrences of the preceding
characters match
(in the following example, the string must begin with one or
more leading zeros)
NumberString = "00125";
preg_match("/^0*/", $NumberString);//returns 1

181

Specifying Quantity
(continued)
The { } quantifiers specify the number of times that a
character must repeat sequentially
(in the following example, the string must contain at least five
characters)
preg_match("/ZIP: .{5}$/", " ZIP: 01562");
// returns 1
The { } quantifiers can also specify the quantity as a range
(in the following example, the string must contain between five
and ten characters)
preg_match("/(ZIP: .{5,10})$/", "ZIP:
01562-2607");// returns 1
182

Specifying Subexpressions
When a set of characters enclosed in
parentheses are treated as a group, they are
referred to as a subexpression or subpattern
(in the example below, the 1 and the area code are
optional, but if included must be in the following format:)
1 (707) 555-1234
preg_match("/^(1 )?(\(.{3}\) )?(.{3})(\.{4})$/

183

Defining Character Classes


Character classes in regular expressions treat
multiple characters as a single item
Characters enclosed with the ([]) metacharacters
represent alternate characters that are allowed in
a pattern match
preg_match("/analy[sz]e/", "analyse");//returns 1
preg_match("/analy[sz]e/", "analyze");//returns 1
preg_match("/analy[sz]e/", "analyce");//returns 0
184

Defining Character Classes


(continued)
The hyphen metacharacter (-) specifies a range
of values in a character class
(the following example ensures that A, B, C, D, or F are
the only values assigned to the $LetterGrade variable)
$LetterGrade = "B";

echo ereg("[A-DF]", $LetterGrade); //


returns true

185

Defining Character Classes


(continued)
The ^ metacharacter (placed immediately after
the opening bracket of a character class)
specifies optional characters to exclude in a
pattern match
(the following example excludes the letter E and G-Z from
an acceptable pattern match in the $LetterGrade
variable)
$LetterGrade = "A";

echo ereg("[^EG-Z]", $LetterGrade); //


returns true
186

Defining Character Classes


(continued)

187

Matching Multiple Pattern


Choices
The | metacharacter is used to specify an
alternate set of patterns
The | metacharacter is essentially the same as
using the OR operator to perform multiple
evaluations in a conditional expression

188

Pattern Modifiers
Pattern modifiers are letters placed after the
closing delimiter that change the default rules for
interpreting matches
The pattern modifier, i, indicates that the case of
the letter does not matter when searching
The pattern modifier, m, allows searches across
newline characters
The pattern modifier, s, changes how the . (period)
metacharacter works
189

Summary
The concatenation operator (.) and the
concatenation assignment operator (.=) can
be used to combine two strings
An escape character tells the compiler or
interpreter that the character following the
escape character has a special purpose. An
escape character combined with one or more
other characters is called an escape sequence

190

Summary (continued)
Simple string syntax allows you to use the
value of a variable within a string by including the
variable name inside a text string with double
quotation marks
The type of structure in which variables are
placed within curly braces inside of a string is
called complex string syntax
The most commonly used string-counting
function is the strlen() function, which
returns the total number of characters in a string
191

Summary (continued)
The str_word_count()function returns the
number of words in a string
The strtoupper(), strtolower(),
ucfirst(), lcfirst(), and ucwords()
functions all change the case of characters in the
string
The substr() function returns the specified
portion of a string

192

Summary (continued)
When applied to text strings, parsing refers to
the act of dividing a string into logical component
substrings or tokens
There are two types of string search and
extraction functions: functions that return a
numeric position in a text string and those that
return a character or substring
You use the str_replace(),
str_ireplace(), and substr_replace()
functions to replace text in strings
193

Summary (continued)
The strtok()function breaks a string into
smaller strings, called tokens
You use the str_split() or explode()
function to split a string into an indexed array, in
which each character in the string becomes a
separate element in the array
The implode() function combines an arrays
elements into a single string, separated by
specified characters
194

Summary (continued)
The strcasecmp() function performs a caseinsensitive comparison of strings, whereas the
strcmp()function performs a case-sensitive
comparison of strings
The similar_text() and levenshtein()
functions are used to determine the similarity of
two strings
You can use the soundex() and metaphone()
functions to determine whether two strings are
pronounced similarly
195

Summary (continued)
Regular expressions are a pattern of specially
formatted strings that can be used to validate the
structure of a string
Regular expressions are made up of both literal
characters and special characters, called
metacharacters, which define the patternmatching rules
In a regular expression, a backslash character (\)
is used to match metacharacters as literal values
196

Summary (continued)
Quantifiers are metacharacters that specify the
number of times a particular match may occur
Subexpressions are characters contained in
parentheses within a regular expression
The format and quantity of the characters in the
subexpression can be defined as a group
A character class is multiple characters
enclosed in square brackets ([]) that are
treated as a single unit
197

Summary (continued)
The | metacharacter allows a string to be
comprised of an alternate set of substrings. The
| metacharacter performs essentially the same
function as the Or (||) operator in conditional
expressions

198

Chapter 4
Handling User Input
2nd Edition

Objectives
In this chapter, you will:
Learn about autoglobal variables
Build XHTML Web forms
Process form data
Handle submitted form data
Create an All-in-One form
Display dynamic data based on a URL token

200

Using Autoglobals
Autoglobals are predefined global arrays that
provide information about server, environment,
and user input

201

Using Autoglobals (continued)


Autoglobals are associative arrays
To access the values in an associative array, place
the elements key in single or double quotation
marks inside the array brackets.
(the following example displays the
SCRIPT_NAME element of the $_SERVER
autoglobal)
$_SERVER["SCRIPT_NAME"];//displays
the path and name of the current
script
202

Building XHTML Web Forms


Web forms are interactive controls that allow
users to enter and submit data to a processing
script
A Web form is a standard XHTML form with two
required attributes in the opening <form> tag:
Action attribute: Identifies the program on the
Web server that will process the form data when
it is submitted
Method attribute: Specifies how the form data
will be sent to the processing script
203

Adding an action Attribute


The opening form tag requires an action
attribute
The value of the action attribute identifies the
program on the Web server that will process the
form data when the form is submitted
<form action="http://www.example.com/
HandleFormInput.php">

204

Adding the method Attribute


The value of the method attribute must be either
post or get
The post method embeds the form data in the
request message
The get method appends the form data to the
URL specified in the forms action attribute

When a Web form is submitted using the post


method, PHP automatically creates and
populates a $_POST array; when the get
method is used, PHP creates and populates a
$_GET array
205

Adding the method Attribute


(continued)
Form fields are sent to the Web server as a
name/value pair
The name portion of the name/value pair
becomes the key of an element in the $_POST or
$_GET array, depending on which method was
used to submit the data
The value portion of the name/value pair is
populated by the data that the user enters in the
input control on the Web form
206

Adding the method Attribute


(continued)
When submitting data using the get method,
form data is appended to the URL specified by
the action attribute
Name/value pairs appended to the URL are
called URL tokens

207

Adding the method Attribute


(continued)
The form data is separated from the URL by a
question mark (?)
the individual elements are separated by an
ampersand (&)
the element name is separated from the value
by an equal sign (=).
Spaces in the name and value fields are
encoded as plus signs (+)

208

Adding the method Attribute


(continued)
all other characters except letters, numbers,
hyphens (-), underscores (_) and periods (.) are
encoded using a percent sign (%) followed by the
two-digit hexadecimal representation of the
characters ASCII value
(the following code shows three form elements
submitted to the process_Scholarship.php script)
http://www.example.net/process_Scholars
hip.php?
fName=John&lName=Smith&Submit=Send+Form
209

Adding the method Attribute


(continued)
Limitations of the get method for submitting
form data
Restricts the number of characters that can be
appended to a single variable to 100
The form values are appended to the URL in plain
text, making a URL request insecure

Advantage of the get method for submitting


form data
Passed values are visible in the Address Bar of
the browser
210

Processing Form Data


A form handler is a program or script that
processes the information submitted from a Web
form
A form handler performs the following:
Verifies that the user entered the minimum
amount of data to process the form
Validates form data
Works with the submitted data
Returns appropriate output as a Web page
211

Retrieving Submitted Data


The PHP script that processes the usersubmitted data is called a form handler.
The values stored in the $_POST array can be
accessed and displayed by the echo statement
as shown below:
$firstName = $_POST['fName'];
$lastName = $_POST['lName'];
echo "Thank you for filling out the
scholarship form, ".$firstName." ".
$lastName . ".";
212

Handling Special Characters


Magic Quotes automatically add a backslash
character to any single quote, double quote, or
NULL character contained in form data that a
user submits to a PHP script

Figure 4-4 Form input string with magic quotes


213

Handling Special Characters


(continued)

214

Handling Special Characters


(continued)
The addslashes() function adds a backslash
before a single or double quote or a NULL
character in user input (if magic quotes is
disabled, this is the alternative to escape a
character before saving to a text file or database)
The stripslashes() function removes a
backslash before a single or double quote or
NULL character in user input (if magic quotes is
enabled, this is required before outputting a string
with the echo statement)
215

Handling Submitted Form Data


It is necessary to validate Web form data to ensure PHP can use the data
The optimal way to ensure valid form data is only allow the user to enter an acceptable
response
Examples of data validation include verifying that
the user did not leave any required fields blank
an e-mail address was entered in the correct format
the user did not exceed the word limit in a comment box

216

Determining if Form Variables


Contain Values
When form data is posted using the post or
get method, all controls except unchecked
radio buttons and checkboxes get sent to the
server even if they do not contain data
The empty() function is used to determine if a
variable contains a value
The empty() function returns FALSE if the
variable being checked has a nonempty and
nonzero value, and a value of TRUE if the
variable has an empty or zero value
217

Validating Entered Data


Validating form data refers to verifying that the
value entered in a field is appropriate for the
data type that should have been entered
The best way to ensure valid form data is to
build the Web form with controls (such as check
boxes, radio buttons, and selection lists) that
only allow the user to select valid responses
Unique information, such as user name,
password, or e-mail must be validated

218

Validating Numeric Data


All data in a Web form is string data and PHP
automatically converts string data to numeric
data if the string is a number
The is_numeric() function is used to
determine if a variable contains a number
The round() function can be used to a numeric
variable with an appropriate number of decimal
places

219

Validating String Data


Regular expression functions are some of the
best tools for verifying that string data meets the
strict formatting required for e-mail addresses,
Web page URLs, or date values
The stripslashes() function removes the
leading slashes for escape sequences
The trim() function removes any leading or
trailing white space from a string

220

Handling Multiple Errors


When processing a Web form, it is best to track
any errors on the form during processing and
then redisplay the form for the user to correct all
the errors at one time

221

Redisplaying the Web Form


A sticky form is used to redisplay the form with
the controls set to the values the user entered
the last time the form was submitted
The following syntax illustrates how to use the
value attribute to display previous submitted
values in sticky form:
<p>First Name: <input type="text"
name="fName" value="<?php echo $firstName;
?>" /></p>
222

Emailing the Web Form


The mail() function is used to send an e-mail
message containing form data in PHP
The basic syntax for this function is

mail(recipient(s), subject, message)


The Address Specifier defines the format of the
e-mail addresses that can be entered as the
recipient argument
Plain e-mail address: jdoe@example.net
Recipients name and e-mail address: Mary
Smith <mary.smith@example.com>
223

Emailing the Web Form


(continued)
The subject argument of the mail() function must include only plain text
with no XHTML tags or character entities unless a special MIME format is
used
The message argument of the mail() function is a text string that must
also be in plain text
A fourth, optional additional_headers argument can include headers
that are standard in most e-mail editors From, Cc, Bcc and Date.

224

Emailing the Web Form


(continued)
With the additional_headers argument
Each header must be on its own line
Each line must start with the header name, followed by a colon, a space, and the value of the
header element
Date: Fri, 03 Apr 2009 16:05:50 -0400
From: Linda M. Jones linda@jones.example.com
CC: Mary R. Jones <mary@jones.example.com>

A successful e-mail message returns a value of TRUE

225

Creating an All-in-One Form


A two-part form has one page that displays the
form and one page that processes the form data
For simple forms that require only minimal
processing, its often easier to use an All-in-One
forma single script used display a Web form
and process its data

226

Validating an All-in-One Form


It uses a conditional to determine if the form has
been submitted or if it is being viewed for the first
time
The isset() function is used to determine if the
$Submit variable has been set
if (isset($Submit)) {
// Validate the data
}

The argument of the isset() function is the name


assigned to the Submit button in the Web form
227

Redisplaying the Web Form


If the submitted data did not pass all validation
checks or no data has been entered, the All-inOne form will display the Web form, for the user
to enter data for the first time or re-enter data
that did not pass validation
if (isset ($_POST['Submit'])) {
// Process the data
}
else {
// Display the Web form
}
228

Displaying Dynamic Content Based


on a URL Token
By passing URL tokens to a PHP script, many
different types of information can be displayed
from the same script
By using a Web page template with static
sections and a dynamic content section, a single
PHP script can produce the same content as
multiple static XHTML pages

229

Using a Web Page Template


A Web template is a single Web page that is
divided into separate sections such as

Header
Button Navigation
Dynamic Content
Footer

The contents of the individual sections are


populated using include files
230

Using Text Hyperlinks for Navigation


When the user clicks on a text hyperlink the
contents that display in the dynamic data section
of the index.htm (home page) are replaced by
the contents referenced by the href attribute
A name/value pair is appended to the index URL
(this attribute and value will be referenced in the
dynamic data section of the index.php file)
The name is user defined
The value is user defined
<a href = "index.php?page=home_page">Home</a>
231

Using Form Image Buttons


for Navigation
Buttons must be enclosed by a opening and closing
<form> tag
<input type = "image" src = "home.jpg" name =
"home" style = "border:0" alt= "Home" />

x- and y- coordinates are sent in the form Button.x


and Button.y where Button is the value of the
name attribute (home)
In PHP, the periods are replaced by underscores for
the $_GET or $_POST array indexes
The $_GET and $_POST array would have two
elements home_x and home_y
232

Displaying the Dynamic Content


The $_REQUEST autoglobal can be used to
access the results from form data sent using
either the get or post methods
The syntax to save the value of the page attribute
to a variable is shown below:
$displayContents = $_REQUEST["page"];

The dynamic content section of the index.php file


will contain the code to determine which content
page to display
233

Displaying the Dynamic Content


(continued)
if (isset($_GET['page'])) {
switch ($_GET['page']) {
case 'About Me':
include('inc_about.html');
break;
case 'home'://display the default page
include('inc_home.html');
break;
default:
include('inc_home.html');
break;
}
}
234

Summary
PHP includes various predefined global arrays,
called autoglobals or superglobals, which
contain client, server, and environment
information that you can use in your scripts
Web forms are standard XHTML Web pages
with interactive controls that allow users to enter
data

235

Summary (continued)
The <form> tag requires an action attribute to
identify the script that will process the submitted
data and a method attribute to identify whether
the data will be sent using the get or post
method
The $_POST autoglobal contains data
submitted from a form using the post method;
the $_GET autoglobal contains data submitted
from a form using the get method or through a
hyperlink
236

Summary (continued)
Web forms may have two components: the data
entry form page and the data processing script
If Magic Quotes is enabled, the PHP scripting
engine inserts an escape character before a
single quotation mark, double quotation mark, or
NULL character in any submitted form data
Magic quotes may be enabled for a PHP server

237

Summary (continued)
The addslashes() function inserts an escape
character before a single quotation mark, double
quotation mark, or NULL character in a string
The stripslashes() function removes the
escape character before a single quotation
mark, double quotation mark, or NULL character
in a string
The first step in processing form data is to
validate the input
238

Summary (continued)
The empty()function determines if the entered
value has an empty or zero value
The is_*() family of functions determines if
the entered value is of the required data type
Regular expressions determine if an entered
string value is formatted correctly for the
required type of entry
The user should be notified of all errors in the
values entered into the form
239

Summary (continued)
Sticky forms are forms that redisplay after an
error has been found
The fields in a sticky form are populated with the
values the user entered previously.
Advanced escaping from XHTML is a
convenient way to display XHTML code within a
PHP code block

240

Summary (continued)
The mail() function is used to send mail from
PHP; it can be used to send form data via e-mail
when the form has been successfully completed
and validated
All-in-One Web forms combine the data entry
form page and the data processing script into a
single script
The isset() function determines if the
entered value has been initialized (or set)
241

Summary (continued)
URL tokens use the get method and additional
data appended to the URL to submit information
to a PHP script
Web templates combine static elements and a
dynamic content section within a Web page
Web templates can use the include()
function within a conditional or switch statement
to display dynamic content from different include
files within the same section of the template
242

Chapter 5
Working with Files
and Directories
2nd Edition

Objectives
In this chapter, you will:
Understand file type and permissions
Work with directories
Upload and download files
Write data to files
Read data from files
Open and close a file stream
Manage files and directories
244

Understanding File Types and


Permissions
File types affect how information is stored in
files and retrieved from them
File permissions determine the actions that a
specific user can and cannot perform on a file

245

Understanding File Types


A binary file is a series of characters or bytes
for which PHP attaches no special meaning
Structure is determined by the application that
reads or writes to the file

A text file has only printable characters and a


small set of control or formatting characters
Text files translate the end-of-line character
sequences such as \n or \r\n to carriage
returns
246

Understanding File Types


(continued)

247

Understanding File Types


(continued)
Different operating systems use different
escape sequences to identify the end of a line:
Use the \n sequence to end a line on a UNIX/Linux
operating system
Use the \n\r sequence to end a line on a Windows
operating system
Use the \r sequence to end a line on a Macintosh
operating system.

248

Understanding File Types


(continued)
Scripts written in a UNIX/Linux text editor
display differently when opened in a Windowsbased text editor

Figure 5-1 Volunteer registration form

249

Working with File Permissions


Files and directories have three levels of access:
User
Group
Other

The three typical permissions for files and


directories are:
Read (r)
Write (w)
Execute (x)
250

Working with File Permissions


(continued)
File permissions are calculated using a four-digit
octal (base 8) value
Octal values encode three bits per digit, which
matches the three permission bits per level of
access
The first digit is always 0
To assign more than one value to an access
level, add the values of the permissions together

251

Working with File Permissions


(continued)

252

Working with File Permissions


(continued)
The chmod() function is used to change the
permissions or modes of a file or directory
The syntax for the chmod() function is
chmod($filename, $mode)

Where $filename is the name of the file to


change and $mode is an integer specifying the
permissions for the file
253

Checking Permissions
The fileperms() function is used to read
permissions associated with a file
The fileperms() function takes one argument
and returns an integer bitmap of the permissions
associated with the file
Permissions can be extracted using the
arithmetic modulus operator with an octal value of
01000

The dococt() function converts a decimal


value to an octal value
254

Reading Directories
The following table lists the PHP functions that
read the names of files and directories

255

Reading Directories
(continued)
The opendir() function is used to iterate
through entries in a directory
A handle is a special type of variable that PHP
used to represent a resource such as a file or a
directory
The readdir() function returns the file and
directory names of an open directory
The directory pointer is a special type of variable
that refers to the currently selected record in a
directory listing
256

Reading Directories
(continued)
The closedir() function is used to close the
directory handle
The following code lists the files in the open
directory and closes the directory.
$Dir = "/var/html/uploads";
$DirOpen = opendir($Dir);
while ($CurFile = readdir($DirOpen)) {
echo $CurFile . "<br />\n";
}
closedir($DirOpen);
257

Reading Directories
(continued)
The following Figure shows the directory listing
for three files: kitten.jpg, polarbear.jpg, and
gorilla.gif

Figure 5-2 Listing of the files subdirectory using the opendir(),


readdir(), and closedir() functions
258

Reading Directories
(continued)
The PHP scripting engine returns the navigation shortcuts
(. and ..) when it reads a directory
The strcmp() function can be used to exclude those
entries

while ($CurFile = readdir($DirOpen))


if ((strcmp($CurFile, '.') != 0) &&
(strcmp($CurFile, '..') != 0))
echo "<a href=\"files/" . $CurFile . "\">" .
$CurFile . "</a><br />";
}

259

Reading Directories
(continued)
The scandir() function returns the names of
the entries in a directory to an array sorted in
ascending alphabetical order
$Dir = "/var/html/uploads";
$DirEntries = scandir($Dir);
foreach ($DirEntries as $Entry) {
echo $Entry . "<br />\n";

}
260

Reading Directories
(continued)

Figure 5-3 Listing of the files subdirectory


using the scandir() function

261

Creating Directories
The mkdir() function creates a new directory
To create a new directory within the current
directory:
Pass just the name of the directory you want to
create to the mkdir() function
mkdir("volunteers");

262

Creating Directories (continued)


To create a new directory in a location
other than the current directory:
Use a relative or an absolute path
mkdir("../event");
mkdir("/bin/PHP/utilities");

263

Creating Directories (continued)

Figure 5-4 Warning that appears if a directory already exists

264

Obtaining File and Directory


Information

265

Obtaining File and Directory


Information (continued)

266

Obtaining File and Directory


Information (continued)
$Dir = "/var/html/uploads";
if (is_dir($Dir)) {
echo "<table border='1' width='100%'>\n";
echo "<tr><th>Filename</th><th>File Size</th>
<th>File Type</th></tr>\n";

$DirEntries = scandir($Dir);
foreach ($DirEntries as $Entry) {
$EntryFullName = $Dir . "/" . $Entry;
echo "<tr><td>" . htmlentities($Entry) . "</td><td>" .
filesize($EntryFullName) . "</td><td>" .
filetype($EntryFullName) . "</td></tr>\n";
}
echo "</table>\n";
}
else
echo "<p>The directory " . htmlentities($Dir) . " does not
exist.</p>";
267

Obtaining File and Directory


Information (continued)

Figure 5-5 Output of script with file and directory


information functions
268

Obtaining File and Directory


Information (continued)
The following table returns additional information
about files and directories:

269

Uploading and Downloading


Files
Web applications allow visitors to upload files to
and from from their local computer (often
referred to as the client)
The files that are uploaded and downloaded may
be simple text files or more complex file types,
such as images, documents, or spreadsheets

270

Selecting the File


Files are uploaded through an XHTML form
using the post method
An enctype attribute in the opening form tag
must have a value of multipart/form-data,
which instructs the browser to post multiple
sections one for regular form data and one for
the file contents

271

Selecting the File


(continued)
The file input field creates a Browse button for
the user to navigate to the appropriate file to
upload
<input type="file"
name="picture_file" />

The MAX_FILE_SIZE (uppercase) attribute of a


hidden form field specifies the maximum number
of bytes allowed in the uploaded file
The MAX_FILE_SIZE hidden field must appear
before the file input field
272

Retrieving the File Information


When the form is posted, information for the
uploaded file is stored in the $_FILES
autoglobal array
The $_FILES[] array contains five elements:
$_FILES['picture_file']['error'] //
Contains the error code associated with
the file

$_FILES['picture_file']['tmp_name'] //
Contains the temporary location of the
file contents
273

Retrieving the File Information


(continued)
// Contains the name of the original file
$_FILES['picture_file']['name']

// Contains the size of the uploaded


file in bytes
$_FILES['picture_file']['size']
// Contains the type of the file
$_FILES['picture_file']['type']

274

Storing the Uploaded File


Uploaded files are either public or private
depending on whether they should be
immediately available or verified first
Public files are freely available to anyone visiting
the Web site
Private files are only available to authorized
visitors

275

Storing the Uploaded File


(continued)
The move_uploaded_file() function moves
the uploaded file from its temporary location to a
permanent destination with the following syntax:
bool move_uploaded_file(string
$filename, string $destination)
$filename is the contents of
$_FILES['filefield']['tmp_name'] and
$destination is the path and filename of the
location where the file will be stored.
276

Storing the Uploaded File


(continued)
The function returns TRUE if the move succeeds,
and FALSE if the move fails
if (move_uploaded_file($_FILES['picture_file']
['tmp_name'], "uploads/" . $_FILES['picture_file']
['name']) === FALSE)
echo "Could not move uploaded file to \"uploads/" .
htmlentities($_FILES['picture_file']['name']) .
"\"<br />\n";
else
echo "Successfully uploaded \"uploads/" .
htmlentities($_FILES['picture_file']['name']) .
"\"<br />\n";
277

Downloading Files
Files in the public XHTML directory structure can
be downloaded with an XHTML hyperlink
Files outside the public XHTML directory require
a three-step process:
Tell the script which file to download
Provide the appropriate headers
Send the file

The header() function is used to return header


information to the Web browser
278

Downloading Files
(continued)

279

Writing an Entire File


PHP supports two basic functions for writing
data to text files:
file_put_contents() function writes or
appends a text string to a file and returns the
number of bytes written to the file
fwrite() function incrementally writes data to a
text file

280

Writing an Entire File


(continued)
The file_put_contents() function writes or
appends a text string to a file
The syntax for the file_put_contents()
function is:
file_put_contents (filename, string[, options])

281

Writing an Entire File


(continued)
$EventVolunteers = " Blair, Dennis\n ";
$EventVolunteers .= " Hernandez, Louis\n ";
$EventVolunteers .= " Miller, Erica\n ";
$EventVolunteers .= " Morinaga, Scott\n ";
$EventVolunteers .= " Picard, Raymond\n ";
$VolunteersFile = " volunteers.txt ";
file_put_contents($VolunteersFile,
$EventVolunteers);

282

Writing an Entire File


(continued)
If no data was written to the file, the function
returns a value of 0
Use the return value to determine whether data
was successfully written to the file
if (file_put_contents($VolunteersFile, $EventVolunteers) > 0)
echo "<p>Data was successfully written to the
$VolunteersFile file.</p>";
else
echo "<p>No data was written to the $VolunteersFile file.</p>";

283

Writing an Entire File


(continued))
The FILE_USE_INCLUDE_PATH constant
searches for the specified filename in the path
that is assigned to the include_path directive
in your php.ini configuration file
The FILE_APPEND constant appends data to
any existing contents in the specified filename
instead of overwriting it

284

Reading an Entire File

285

Reading an Entire File


(continued)
The file_get_contents() function reads the
entire contents of a file into a string
$DailyForecast = "<p><strong>San Francisco daily weather
forecast</strong>: Today: Partly cloudy. Highs from the 60s to
mid 70s. West winds 5 to 15 mph. Tonight: Increasing clouds. Lows
in the mid 40s to lower 50s. West winds 5 to 10 mph.</p>";
file_put_contents("sfweather.txt", $DailyForecast);

$SFWeather = file_get_contents("sfweather.txt");
echo $SFWeather;

286

Reading an Entire File


(continued)
The readfile() function displays the
contents of a text file along with the file size to a
Web browser
readfile("sfweather.txt");

287

Reading an Entire File


(continued)
The file() function reads the entire contents
of a file into an indexed array
Automatically recognizes whether the lines in a
text file end in \n, \r, or \r\n
$January = " 61, 42, 48\n ";
$January .= "62, 41, 49\n ";
$January .= " 62, 41, 49\n ";
$January .= " 64, 40, 51\n ";
$January .= " 69, 44, 55\n ";
$January .= " 69, 45, 52\n ";
$January .= " 67, 46, 54\n ";
file_put_contents("sfjanaverages.txt", $January);
288

Reading an Entire File


(continued)
$JanuaryTemps = file("sfjanaverages.txt");
for ($i=0; $i<count($JanuaryTemps); ++$i) {
$CurDay = explode(", ", $JanuaryTemps[$i]);
echo "<p><strong>Day " . ($i + 1) . "</strong><br />";
echo "High: {$CurDay[0]}<br />";
echo "Low: {$CurDay[1]}<br />";
echo "Mean: {$CurDay[2]}</p>";
}

289

Reading an Entire File


(continued)

Figure 5-13 Output of individual lines in a text file


290

Opening and Closing File


Streams
A stream is a channel used for accessing a
resource that you can read from and write to
The input stream reads data from a resource
(such as a file)
The output stream writes data to a resource
1. Open the file stream with the fopen() function
2. Write data to or read data from the file stream
3. Close the file stream with the fclose() function
291

Opening a File Stream


A handle is a special type of variable that PHP
uses to represent a resource such as a file
The fopen() function opens a handle to a file
stream
The syntax for the fopen() function is:
open_file =

fopen("text file", " mode");

A file pointer is a special type of variable that


refers to the currently selected line or character
in a file
292

Opening a File Stream


(continued)

293

Opening a File Stream


(continued)
$VolunteersFile = fopen(volunteers.txt",
r+");

Figure 5-15 Location of the file pointer when the fopen()


function uses a mode argument of r+
294

Opening a File Stream


(continued)
$VolunteersFile = fopen(volunteers.txt",
a+");

Figure 5-16 Location of the file pointer when the fopen()


function uses a mode argument of a+
295

Closing a File Stream


Use the fclose function when finished working
with a file stream to save space in memory
Use the statement fclose($handle); to
ensure that the file doesnt keep taking up space
in your computers memory and allow other
processes to read to and write from the file

296

Writing Data Incrementally


Use the fwrite() function to incrementally
write data to a text file
The syntax for the fwrite() function is:
fwrite($handle, data[, length]);

The fwrite() function returns the number of


bytes that were written to the file
If no data was written to the file, the function
returns a value of 0
297

Locking Files
To prevent multiple users from modifying a file
simultaneously use the flock() function
The syntax for the flock() function is:
flock($handle, operation)

298

Reading Data Incrementally

The fgets() function uses the file pointer to iterate


through a text file
299

Reading Data Incrementally


(continued)
You must use fopen() and fclose() with the
functions listed in Table 5-10
Each time you call any of the functions in Table
5-10, the file pointer automatically moves to the
next line in the text file (except for fgetc())
Each time you call the fgetc() function, the file
pointer moves to the next character in the file

300

Managing Files and Directories


PHP can be used to manage files and the
directories that store them
Among the file directory and management tasks
for files and directories are

Copying
Moving
Renaming
Deleting

301

Copying and Moving Files


Use the copy() function to copy a file with PHP
The function returns a value of TRUE if it is
successful or FALSE if it is not
The syntax for the copy() function is:
copy(source, destination)

For the source and destination arguments:


Include just the name of a file to make a copy in
the current directory, or
Specify the entire path for each argument
302

Copying and Moving Files


(continued)
if (file_exists(" sfweather.txt ")) {
if(is_dir(" history ")) {
if (copy(" sfweather.txt ",
" history\\sfweather01-27-2006.txt "))
echo " <p>File copied successfully.</p> ";
else
echo " <p>Unable to copy the file!</p> ";
}
else
echo (" <p>The directory does not exist!</p> ");
}
else
echo (" <p>The file does not exist!</p> ");

303

Renaming Files and Directories


Use the rename() function to rename a file or
directory with PHP
The rename() function returns a value of true if
it is successful or false if it is not
The syntax for the rename() function is:
rename(old_name, new_name)

304

Removing Files and Directories


Use the unlink() function to delete files and
the rmdir() function to delete directories
Pass the name of a file to the unlink()
function and the name of a directory to the
rmdir() function
Both functions return a value of true if successful
or false if not
Use the file_exists() function to determine
whether a file or directory name exists before
you attempt to delete it
305

Summary
In PHP, a file can be one of two types: binary or
text
A binary file is a series of characters or bytes
for which PHP attaches no special meaning
A text file has only printable characters and a
small set of control of formatting characters
A text file translates the end-of-line character
sequences in code display
The UNIX/Linux platforms end a line with the \n
sequence
306

Summary (continued)
The Windows platforms end a line with the \n\r
sequence
The Macintosh platforms end a line with the \r
sequence
Files and directories have three levels of access:
user, group, and other
Typical file and directory permissions include
read, write, and execute
PHP provides the chmod() function for
changing the permissions of a file within PHP
307

Summary (continued)
The syntax for the chmod()function is
chmod($filename, $mode)
The chmod() function uses a four-digit octal
value to assign permissions
The fileperms(), which takes filename as
the only parameter, returns a bitmap of the
permissions associated with a file
The opendir() function iterates through the
entries in a directory
308

Summary (continued)
A handle is a special type of variable that
represents a resource, such as a file or directory
To iterate through the entries in a directory, you
open a handle to the directory with the
opendir() function
Use the readdir() function to return the file
and directory names from the open directory
Use the closedir() function to close a
directory handle
309

Summary (continued)
The scandir() function returns an indexed
array of the files and directories ( in ascending
alphabetical order) in a specified directory
The mkdir(), with a single name argument,
creates a new directory
The is_readable(), is_writeable(), and
is_executable() functions check the the file
or directory to determine if the PHP scripting
engine has read, write, or execute permissions,
respectively
310

Summary (continued)
A symbolic link, which is identified with the
is_link() is a reference to a file not on the
system
The is_dir() determines if a directory exists
Directory information functions provide file
access dates, file owner, and file type
Uploading a file refers to transferring the file to a
Web server

311

Summary (continued)
Setting the enctype attribute of the opening
from tag to multipart/form-data instructs the
browser to post one section for regular form data
and one section for file contents
The file input type creates a browse button
that allows the user to navigate to a file to
upload
To limit the size of the file upload, above the file
input field, insert a hidden field with an attribute
MAX_FILE_SIZE and a value in bytes
312

Summary (continued)
An uploaded files information (error code,
temporary file name, filename, size, and type) is
stored in the $_FILES array
MIME (Multipurpose Internet Mail Extension)
generally classifies the file upload as in
image.gif, image.jpg, text/plain, or
text/html
The move_uploaded_file() function moves
the uploaded file to its permanent destination

313

Summary (continued)
The file_put_contents() function writes or
appends a text string to a file and returns the
number of bytes written to the file
The FILE_APPEND constant appends data to
any existing contents in the specified filename
instead of overwriting it
The file_get_contents() and readfile()
functions read the entire contents of a file into a
string
314

Summary (continued)
A stream is a channel that is used for accessing
a resource to which you may read, and write.
The input stream reads data from a resource,
such as a file
The output stream writes data to a resource,
such as a file
The fopen() opens a handle to a file stream
using the syntax $open_file =
fopen("text file", "mode");
315

Summary (continued)
A file pointer is a variable that refers to the
currently selected line or character in a file
Mode arguments used with the fopen()
function specifies if the file is opened for
reading, writing, or executing, and the indicates
the location of the file pointer
The fclose() function with a syntax of
fclose($handle); is used to close a file
stream
316

Summary (continued)
The fwrite() incrementally writes data to a
text file
To prevent multiple users from modifying a file
simultaneously use the flock() function
A number of PHP functions are available to
iterate through a text file by line or character
Use the copy() function to copy a file with PHP
Use the rename() function to rename a file or
directory with PHP
317

Summary (continued)
The unlink() function is used to delete files
and the rmdir() function is used to delete
directories
In lieu of a move function, the rename()
function renames a file and specifies a new
directory to store the renamed file

318

Chapter 6
Manipulating Arrays
2nd Edition

Objectives
In this chapter, you will:
Manipulate array elements
Declare and initialize associative arrays
Iterate through an array
Find and extract elements and values
Sort, combine, and compare arrays
Understand multidimensional arrays
Use arrays in Web forms
320

Manipulating Elements
if (isset($_POST['submit'])) {
$Subject = stripslashes($_POST['subject']);
$Name = stripslashes($_POST['name']);
$Message = stripslashes($_POST['message']);
// Replace any '~' characters with '-' characters
$Subject = str_replace("~", "-", $Subject);
$Name = str_replace("~", "-", $Name);
$Message = str_replace("~", "-", $Message);
$MessageRecord = "$Subject~$Name~$Message\n";
$MessageFile = fopen("MessageBoard/messages.txt", "ab");
if ($MessageFile === FALSE)
echo "There was an error saving your message!\n";
else {
fwrite($MessageFile, $MessageRecord);
fclose($MessageFile);
echo "Your message has been saved.\n";
}
}

321

Manipulating Elements
(continued)
<h1>Post New Message</h1>
<hr />
<form action="PostMessage.php" method="POST">
<strong>Subject:</strong> <input type="text" name="subject" />
<strong>Name:</strong> <input type="text" name="name" /><br />
<textarea name="message" rows="6" cols="80"></textarea><br />
<input type="submit" name="submit" value="Post Message" />
<input type="reset" name="reset" value="Reset Form" />
</form>
<hr />
<a href="MessageBoard.php">View Messages</a>

322

Manipulating Elements
(continued)

Figure 6-1 Post New Message page of the Message Board


323

Manipulating Elements
(continued)
<h1>Message Board</h1>
<?php
?>
<p>
<a href="PostMessage.php">Post New Message</a>
</p>
if ((!file_exists("MessageBoard/messages.txt")) ||
(filesize("MessageBoard/messages.txt") == 0))
echo "<p>There are no messages posted.</p>\n";
}
else {
$MessageArray = file("MessageBoard/messages.txt");
echo "<table style=\"background-color:lightgray\"
border=\"1\" width=\"100%\">\n";
$count = count($MessageArray);
324

Manipulating Elements
(continued)

for ($i = 0; $i < $count; ++$i) {


$CurrMsg = explode("~", $MessageArray[$i]);
echo "
<tr>\n";
echo "
<td width=\"5%\"
align=\"center\"><strong>" . ($i + 1) .
"</strong></td>\n";
echo "
<td
width=\"95%\"><strong>Subject:</strong> " .
htmlentities($CurrMsg[0]) . "<br />";
echo "<strong>Name:</strong> " .
htmlentities($CurrMsg[1]) . "<br />";
echo "<u><strong>Message</strong></u><br />" .
htmlentities($CurrMsg[2]) . "</td>\n";
echo "
</tr>\n";
}
echo "</table>\n";

325

Manipulating Elements
(continued)

Figure 6-2 Message Board page of the Message Board


326

Adding and Removing Elements


from the Beginning of an Array
The array_shift() function removes the first
element from the beginning of an array
Pass the name of the array whose first element
you want to remove

The array_unshift() function adds one or


more elements to the beginning of an array
Pass the name of an array followed by commaseparated values for each element you want to
add
327

Adding and Removing Elements from


the Beginning of an Array (continued)
$TopSellers = array(
"Chevrolet Impala",
"Chevrolet Malibu",
"Chevrolet Silverado",
"Ford F-Series",
"Toyota Camry",
"Toyota Corolla",
"Nissan Altima",
"Honda Accord",
"Honda Civic",
"Dodge Ram");
array_shift($TopSellers);
array_unshift($TopSellers, "Honda CR-V");
echo "<pre>\n";
print_r($TopSellers);
echo "</pre>\n";

328

Adding and Removing Elements from


the Beginning of an Array (continued)

Figure 6-3 Output of an array modified with the array_shift()


and array_unshift() functions
329

Adding and Removing Elements


from the End of an Array
The array_pop() function removes the last
element from the end of an array
Pass the name of the array whose last
element you want to remove

The array_push() function adds one or more


elements to the end of an array
Pass the name of an array followed by
comma-separated values for each element
you want to add
330

Adding and Removing Elements from


the End of an Array (continued)
$HospitalDepts = array(
"Anesthesia",
"Molecular Biology",
"Neurology",
"Pediatrics");
array_pop($HospitalDepts); // Removes "Pediatrics"
array_push($HospitalDepts, "Psychiatry", "Pulmonary
Diseases");

331

Adding and Removing Elements


Within an Array
The array_splice() function adds or
removes array elements
The array_splice() function renumbers the
indexes in the array
The syntax for the array_splice() function
is:
array_splice(array_name, start,
characters_to_delete, values_to_insert);

332

Adding and Removing Elements


Within an Array (continued)
To add an element within an array, include a
value of 0 as the third argument of the
array_splice() function
$HospitalDepts = array(
"Anesthesia",
// first element (0)
"Molecular Biology",
// second element (1)
"Neurology",
// third element (2)
"Pediatrics");
// fourth element (3)
array_splice($HospitalDepts, 3, 0, "Ophthalmology");
333

Adding and Removing Elements


Within an Array (continued)
To add more than one element within an array,
pass the array() construct as the fourth
argument of the array_splice() function
Separate the new element values by commas
$HospitalDepts = array(
"Anesthesia",
//
"Molecular Biology",
//
"Neurology",
//
"Pediatrics");
//
array_splice($HospitalDepts,
"Otolaryngology"));

first element (0)


second element (1)
third element (2)
fourth element (3)
3, 0, array("Opthalmology",

334

Adding and Removing Elements


Within an Array (continued)
Delete array elements by omitting the fourth
argument from the array_splice() function
$HospitalDepts = array(
"Anesthesia",
// first element (0)
"Molecular Biology",
// second element (1)
"Neurology",
// third element (2)
"Pediatrics");
// fourth element (3)
array_splice($HospitalDepts, 1, 2);

335

Adding and Removing Elements


Within an Array (continued)
The unset() function removes array elements
and other variables
Pass to the unset() function the array name
and index number of the element you want to
remove
To remove multiple elements, separate each
index name and element number with commas
unset($HospitalDepts[1], $HospitalDepts[2]);

336

Removing Duplicate Elements


The array_unique() function removes
duplicate elements from an array
Pass to the array_unique() function the
name of the array from which you want to
remove duplicate elements
The array_values() and array_unique()
functions do not operate directly on an array
The array_unique() function does renumber
the indexes after removing duplicate values in
an array
337

Removing Duplicate Elements


(continued)
$TopSellers = array(
"Ford F-Series", "Chevrolet Silverado", "Toyota Camry",
"Honda Accord", "Toyota Corolla", "Ford F-Series", "Honda
Civic",
"Honda CR-V", "Honda Accord", "Nissan Altima", "Toyota Camry",
"Chevrolet Impala", "Dodge Ram", "Honda CR-V");
echo "<p>The 2008 top selling vehicles are:</p><p>";
$TopSellers = array_unique($TopSellers);
$TopSellers = array_values($TopSellers);
for ($i=0; $i<count($ TopSellers); ++$i) {
echo "{$TopSellers[$i]}<br />";
}
echo "</p>";

338

Removing Duplicate Elements


(continued)

Figure 6-4 Output of an array after removing duplicate values


with the array_unique() function
339

Declaring and Initializing


Associative Arrays
With associative arrays, you specify an
elements key by using the array operator (=>)
The syntax for declaring and initializing an
associative array is:
$array_name = array(key=>value, ...);

Figure 6-5 Output of array with associative and indexed elements


340

Declaring and Initializing


Associative Arrays (continued)
$Territories[100] = "Nunavut";
$Territories[] = "Northwest Territories";
$Territories[] = "Yukon Territory";
echo "<pre>\n";
print_r($Territories);
echo "</pre>\n";
echo '<p>The $Territories array consists of ',
count($Territories), " elements.</p>\n";

Figure 6-6 Output of an array with a starting index of 100


341

Iterating Through an Array


The internal array pointer refers to the
currently selected element in an array

342

Iterating Through an Array


(continued)

Figure 6-8 Output of an array without advancing the internal


array pointer
343

Finding and Extracting


Elements and Values
One of the most basic methods for finding a value
in an array is to use a looping statement to iterate
through the array until you find the value
Rather than write custom code to find a value,
use the in_array() and array_search()
functions to determine whether a value exists in
an array

344

Determining if a Value Exists


The in_array() function returns a Boolean
value of true if a given value exists in an array
The array_search() function determines
whether a given value exists in an array and:
Returns the index or key of the first matching
element if the value exists, or
Returns FALSE if the value does not exist
if (in_array("Neurology", $HospitalDepts))
echo "<p>The hospital has a Neurology department.</p>";
345

Determining if a Key Exists


The array_key_exists() function
determines whether a given index or key exists
You pass two arguments to the
array_key_exists() function:
The first argument represents the key to
search for
The second argument represents the name
of the array in which to search

346

Determining if a Key Exists


(continued)
$ScreenNames["Dancer"] = "Daryl";
$ScreenNames["Fat Man"] = "Dennis";
$ScreenNames["Assassin"] = "Jennifer";
if (array_key_exists("Fat Man", $ScreenNames))
echo "<p>{$ScreenNames['Fat Man']} is already
'Fat Man'.</p>\n";
else {
$ScreenNames["Fat Man"] = "Don";
echo "<p>{$ScreenNames['Fat Man']} is now
'Fat Man'.</p>";
}
347

Returning a Portion of an Array


The array_slice() function returns a portion
of an array and assigns it to another array
The syntax for the array_slice() function is:
array_slice(array_name, start, characters_to_return);

348

Returning a Portion of an Array


(continued)
// This array is ordered by sales, high to low.
$TopSellers = array("Ford F-Series", "Chevrolet Silverado",
"Toyota Camry", "Honda Accord", "Toyota Corolla", "Honda
Civic", "Nissan Altima", "Chevrolet Impala", "Dodge Ram",
"Honda CR-V");
$FiveTopSellers = array_slice($TopSellers, 0, 5);
echo "<p>The five best-selling vehicles for 2008
are:</p>\n";
for ($i=0; $i<count($FiveTopSellers); ++$i) {
echo "{$FiveTopSellers[$i]}<br />\n";
}

349

Returning a Portion of an Array


(continued)

Figure 6-11 Output of an array returned with the


array_slice() function
350

Sorting Arrays
The most commonly used array sorting
functions are:
sort() and rsort() for indexed arrays
ksort() and krsort() for associative arrays

351

Sorting Arrays (continued)

352

Sorting Arrays (continued)

353

Sorting Arrays (continued)

If the sort() and rsort() functions are used


on an associative array, the keys are replaced
with indexes

354

Sorting Arrays (continued)

Figure 6-12 Output of an array after applying the sort() and rsort() functions
355

Sorting Arrays (continued)

Figure 6-13 Output of an associative array after sorting with the sort() function

356

Sorting Arrays (continued)

Figure 6-14 Output of an associative array after sorting


with the asort() function
357

Sorting Arrays (continued)

Figure 6-15 Output of an associative array


after sorting with the ksort() function
358

Combining Arrays
To append one array to another, use the addition
(+) or the compound assignment operator (+=)
To merge two or more arrays use the
array_merge() function
The syntax for the array_merge() function is:
new_array = array_merge($array1, $array2,
$array3, ...);

359

Combining Arrays (continued)


$Provinces = array("Newfoundland and Labrador",
"Prince Edward Island", "Nova Scotia", "New
Brunswick", "Quebec", "Ontario", "Manitoba",
"Saskatchewan", "Alberta", "British
Columbia");
$Territories = array("Nunavut", "Northwest
Territories", "Yukon Territory");
$Canada = $Provinces + $Territories;
echo "<pre>\n";
print_r($Canada);
echo "</pre>\n";
360

Combining Arrays (continued)

Figure 6-12 Output of two indexed arrays combined with the


addition operator
361

Comparing Arrays
The array_diff() function returns an array of
elements that exist in one array but not in any
other arrays to which it is compared
The syntax for the array_diff() function is:
new_array = array_diff($array1, $array2,
$array3, ...);

The array_intersect() function returns an


array of elements that exist in all of the arrays
that are compared
362

Comparing Arrays (continued)


The syntax for the array_intersect()
function is:
new_array = array_intersect($array1,
$array2, $array3, ...);

363

Comparing Arrays (continued)


$ProvincialCapitals = array("Newfoundland and Labrador"=>"St.
John's", "Prince Edward Island"=>"Charlottetown", "Nova
Scotia"=>"Halifax", "New Brunswick"=>"Fredericton",
"Quebec"=>"Quebec City", "Ontario"=>"Toronto",
"Manitoba"=>"Winnipeg", "Saskatchewan"=>"Regina",
"Alberta"=>"Edmonton", "British Columbia"=>"Victoria");
$TerritorialCapitals = array("Nunavut"=>"Iqaluit", "Northwest
Territories"=>"Yellowknife", "Yukon Territory"=>"Whitehorse");
$CanadianCapitals = $ProvincialCapitals + $TerritorialCapitals;
echo "<pre>\n";
print_r($CanadianCapitals);
echo "</pre>\n";

364

Comparing Arrays (continued)

Figure 6-20 Output of an array created with the


array_intersect() function
365

Comparing Arrays (continued)


$Provinces = array("Newfoundland and Labrador",
"Prince Edward Island", "Nova Scotia", "New
Brunswick", "Quebec", "Ontario", "Manitoba",
"Saskatchewan", "Alberta", "British
Columbia");
$Territories = array("Nunavut", "Northwest
Territories", "Yukon Territory");
$Canada = array_merge($Provinces, $Territories);

366

Creating Two-Dimensional
Indexed Arrays
A multidimensional array consists of multiple
indexes or keys
A two-dimensional array has two sets of
indexes or keys

367

Creating Two-Dimensional
Indexed Arrays (continued)
$Gallons = array(
128, // ounces
16, // cups
8, // pints
4 // quarts
);

368

Creating Two-Dimensional
Indexed Arrays (continued)
$Ounces = array(1, 0.125, 0.0625, 0.03125,
0.0078125);
$Cups = array(8, 1, 0.5, 0.25, 0.0625);
$Pints = array(16, 2, 1, 0.5, 0.125);
$Quarts = array(32, 4, 2, 1, 0.25);
$Gallons = array(128, 16, 8, 4, 1);

369

Creating Two-Dimensional
Indexed Arrays (continued)
$VolumeConversions = array($Ounces, $Cups,
$Pints, $Quarts, $Gallons);

370

Creating Two-Dimensional
Associative Arrays
$Ounces = array("ounces" => 1, "cups" => 0.125, "pints" =>
0.0625, "quarts" => 0.03125, "gallons" => 0.0078125);
$Cups = array("ounces" => 8, "cups" => 1, "pints" =>0.5,
"quarts" => 0.25, "gallons" => 0.0625);
$Pints = array("ounces" => 16, "cups" => 2, "pints" =>1,
"quarts" => 0.5, "gallons" => 0.125);
$Quarts = array("ounces" => 32, "cups" => 4, "pints" =>2,
"quarts" => 1, "gallons" => 0.25);
$Gallons = array("ounces" => 128, "cups" => 16, "pints"
=>8, "quarts" => 4, "gallons" => 1);

371

Creating Two-Dimensional
Associative Arrays (continued)

Figure 6-21 Elements and keys in the


$VolumeConversions[ ] array
372

Creating Multidimensional
Arrays with a Single Statement
$VolumeConversions = array(
array(1, 0.125, 0.0625, 0.03125, 0.0078125), // Ounces
array(8, 1, 0.5, 0.25, 0.0625), // Cups
array(16, 2, 1, 0.5, 0.125), // Pints
array(32, 4, 2, 1, 0.25), // Quarts
array(128, 16, 8, 4, 1) // Gallons
);

373

Working with Additional


Dimensions

374

Using Arrays in Web Forms


Store form data in an array by appending an
opening and closing ([]) to the value of the
name attribute
Data from any element with the same value for
the name attribute will be appended to an array
with that name

375

Using Arrays in Web Forms


(continued)
<form method='post' action='ProcessForm.php'>
<p>Enter the first answer:
<input type='text' name='answers[]' /></p>
<p>Enter the second answer:
<input type='text' name='answers[]' /></p>
<p>Enter the third answer:
<input type='text' name='answers[]' /></p>
<input type='submit' name='submit'
value='submit' />
</form>
376

Using Arrays in Web Forms


(continued)
if (is_array($_POST['answers')) {
$Index = 0;
foreach ($_POST['answers'] as $Answer) {
++$Index;
echo "The answer for question $Index
is '$Answer'<br />\n";
}
}

377

Using Arrays in Web Forms


(continued)

Figure 6-22 Output of an array posted from a Web form

378

Using Multidimensional Array


Notation
Multidimensional array notation can also be
used to process posted form information
if (is_array($_POST['answers')) {
$count = count($_POST['answers']);
for ($i=0; $i<$count; ++$i) {
echo "The answer for question " .
($i+1) . " is '{$_POST['answers'][$i]}'<br
/>\n";
}
}
379

Creating an Associative Forms


Array
<form method='post' action='ProcessForm.php'>
<p>Enter the first answer:
<input type='text' name='answers[Question 1]' /></p>
<p>Enter the second answer:
<input type='text' name='answers[Question 2]' /></p>
<p>Enter the third answer:
<input type='text' name='answers[Question 3]' /></p>
<input type='submit' name='submit' value='submit' />
</form>

380

Summary
The array_shift() function removes the first
element from the beginning of an array
The array_unshift() function adds one or
more elements to the beginning of an array
The array_pop() function removes the last
element from the end of an array
The array_push() function adds one or more
elements to the end of an array
The array_splice() function adds or
removes array elements
381

Summary (continued)
The unset() function removes array elements
and other variables
The array_values() function renumbers an
indexed arrays elements
The array_unique() function removes
duplicate elements from an array
The in_array() function returns a Boolean
value of TRUE if a given value exists in an array
The array_search() function determines
whether a given value exists in an array
382

Summary (continued)
The array_key_exists() function
determines whether a given index or key exists
The array_slice() function returns a portion
of an array and assigns it to another array
The array_merge() function merges two or
more arrays
The array_diff() function returns an array of
elements that exist in one array but not in any
other arrays to which it is compared
383

Summary (continued)
The array_intersect() function returns an
array of elements that exist in all of the arrays
that are compared
A multidimensional array consists of multiple
sets of indexes or keys
A two-dimensional array has two sets of
indexes or keys
When array notation is used in the name of a
Web form input, the value gets stored in a
nested array within the $_POST or $_GET array
384

Summary (continued)
When using associative array notation in a Web
form, you omit the quotation marks around the
key name

385

Chapter 7
Working with Databases
and MySQL
2nd Edition

Objectives
In this chapter, you will:
Study the basics of databases and MySQL
Work with MySQL databases
Define database tables
Modify user privileges
Work with database records
Work with phpMyAdmin

387

Introduction to Databases
A database is an ordered collection of
information from which a computer program
can quickly access information
Each row in a database table is called a record
A record in a database is a single complete set
of related information
Each column in a database table is called a field
Fields are the individual categories of
information stored in a record
388

Introduction to Databases
(continued)

Figure 7-1 Employee directory database


389

Introduction to Databases
(continued)
A flat-file database stores information in a
single table
A relational database stores information
across multiple related tables

390

Understanding Relational
Databases
Relational databases consist of one or more
related tables
A primary table is the main table in a
relationship that is referenced by another table
A related table (or child table) references a
primary table in a relational database
A primary key is a field that contains a unique
identifier for each record in a primary table

391

Understanding Relational
Databases (continued)
A primary key is a type of index, which identifies
records in a database to make retrievals and
sorting faster
A foreign key is a field in a related table that
refers to the primary key in a primary table
Primary and foreign keys link records across
multiple tables in a relational database

392

One-to-One Relationships
A one-to-one relationship exists between two
tables when a related table contains exactly one
record for each record in the primary table
Create one-to-one relationships to break
information into multiple, logical sets
Information in the tables in a one-to-one
relationship can be placed within a single table
Make the information in one of the tables
confidential and accessible only by certain
individuals
393

One-to-One Relationships
(continued)

Figure 7-2 One-to-one relationship


394

One-to-Many Relationship
A one-to-many relationship exists in a
relational database when one record in a
primary table has many related records in a
related table
Breaking tables into multiple related tables to
reduce redundant and duplicate information is
called normalization
Provides a more efficient and less redundant
method of storing this information in a database
395

One-to-Many Relationship
(continued)

Figure 7-3 Table with redundant information


396

One-to-Many Relationship
(continued)

Figure 7-4 One-to-many relationship


397

Many-to-Many Relationship
A many-to-many relationship exists in a
relational database when many records in one
table are related to many records in another
table
A junction table creates a one-to-many
relationship for each of the two tables in a
many-to-many relationship
A junction table contains foreign keys from the
two tables
398

Working with Database


Management Systems
A database management system (or DBMS) is
an application or collection of applications used to
access and manage a database
A schema is the structure of a database including
its tables, fields, and relationships
A flat-file database management system is a
system that stores data in a flat-file format
A relational database management system (or
RDBMS) is a system that stores data in a
relational format
399

Working with Database


Management Systems
(continued)

Figure 7-5 Many-to-many relationship


400

Working with Database


Management Systems
(continued)
Important aspects of database management
systems:
The structuring and preservation of the
database file
Ensuring that data is stored correctly in a
databases tables, regardless of the database
format
Querying capability

401

Working with Database


Management Systems
(continued)
A query is a structured set of instructions and

criteria for retrieving, adding, modifying, and


deleting database information
Structured query language (or SQL) is a
standard data manipulation language used
among many database management systems
Open database connectivity (or ODBC) allows
ODBC-compliant applications to access any
data source for which there is an ODBC driver
402

Getting Started with


MySQL
The MySQL Monitor is a command-line
program for manipulating MySQL databases
Connect to the MySQL server using a
command-line connect
Commands are entered at the mysql->
command prompt in the console window

403

Logging in to MySQL
Enter the following command:
mysql h host u user p

Two accounts are created:


Anonymous user account allows login without
specifying a username or password
root account (the primary administrative account
for MySQL) is created without a password
mysql u root

Log out with the exit or quit commands


404

Logging in to MySQL
(continued)
$ mysql h php_db -u dongosselin -p[ENTER]
Enter password: **********[ENTER]
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 6611 to server version: 4.1.9nt
Type 'help;' or '\h' for help. Type '\c' to clear the
buffer.
mysql>

Use the up and down arrow keys on the keyboard


to scroll through previously entered commands
405

Logging in to MySQL
(continued)

Figure 7-6 MySQL Monitor on a Windows platform


406

Understanding MySQL
Identifiers
An alias is an alternate name used to refer to a
table or field in SQL statements
The case sensitivity of database and table
identifiers depends on the operating system
Not case sensitive on Windows platforms
Case sensitive on UNIX/Linux systems

MySQL stores each database in a directory of


the same name as the database identifier
Field and index identifiers are case insensitive on
all platforms
408

Understanding MySQL
Identifiers (continued)
Identifiers that must be quoted using the
backtick, or single quote, character (`)are
An identifier that includes any character except
standard alphanumeric characters, underscores
(_) or dollar signs ($)
Any identifier that contains one or more space
characters
An identifier that is a reserved word in MySQL
An identifier made entirely of numeric digits
An identifier that contains a backtick character
409

Getting Help with MySQL


Commands

410

Creating Databases
Use the CREATE DATABASE statement to create
a new database:
mysql> CREATE DATABASE vehicle_fleet;[ENTER]

To use a new database, select it by executing


the USE DATABASE statement

411

Selecting a Database
Use the DATABASE() function to return the
name of the currently active database
mysql> SELECT DATABASE();[ENTER]

View the available databases using the SHOW


DATABASES statement
mysql> SHOW databases;[ENTER]

Use the DROP DATABASE statement to remove


all tables and delete a database
mysql> DROP DATABASE database;
412

Defining Database Tables


Data types that are assigned to fields determine
how much storage space the computer allocates
for the data in the database
Choose the smallest data type possible for each
field

413

Defining Database Tables


(continued)

414

Creating Tables
Use the CREATE TABLE statement to create a
new table and define the column names and
data types for each column
mysql> CREATE TABLE vehicles
(license VARCHAR(10), make VARCHAR(25),
model VARCHAR(50), miles FLOAT,
assigned_to VARCHAR(40));[ENTER]

415

Viewing Table Structure


Use the DESCRIBE table_name statement to view the structure of the table

416

Changing Table Field Names


Use the ALTER TABLE to change the name of an
existing field in a table using the following syntax
ALTER TABLE table_name ADD [COLUMN] (column_name
column_type [, column_name column_type ...]);

In MySQL Monitor, enter the following:


mysql> ALTER TABLE vehicles ADD COLUMN (model_year
INT);[ENTER]

417

Modifying Column Types


Use the ALTER TABLE to rename columns of an existing
field in a table using the following syntax
ALTER TABLE table_name CHANGE [COLUMN] column_name
new_name column_type;

In MySQL Monitor, enter the following:


mysql> ALTER TABLE vehicles CHANGE COLUMN miles mileage
FLOAT;[ENTER]

418

Renaming Columns
Use the ALTER TABLE to rename columns using the
following syntax
ALTER TABLE table_name MODIFY [COLUMN] column_name
column_type;

In MySQL Monitor, enter the following:


mysql> ALTER TABLE vehicles MODIFY COLUMN
model_year SMALLINT;[ENTER]

419

Renaming Tables
Use the ALTER TABLE to change the name of an
existing table using the following syntax
ALTER TABLE table_name RENAME [TO] new_name;
mysql> ALTER TABLE vehicles RENAME TO
company_cars;[ENTER]

420

Removing Columns
Use the ALTER TABLE to remove an existing field from a
table using the following syntax
ALTER TABLE table_name DROP [COLUMN]
column_name;
mysql> ALTER TABLE company_cars DROP COLUMN
assigned_to;[ENTER]

421

Deleting Tables
Execute the DROP TABLE statement to remove all data and the
table definition from a database
DROP TABLE table;

In MySQL Monitor, enter the following at the mysql> prompt:


mysql> DROP TABLE company_cars;[ENTER]

You must be logged in as the root user or have DROP


privileges to delete a table.

422

Modifying User Privileges


Privileges are actions and operations a user
can perform with a table or a database
For security purposes, user accounts should
only be assigned the minimum necessary
privileges to perform given tasks

423

Modifying User Privileges


(continued)

424

Granting Privileges
The syntax for the GRANT statement is:
GRANT privilege [(column)] [, privilege [(columns)]] ...
ON {table | * | *.* | database.*}
TO user [IDENTIFIED BY 'password'];

The GRANT statement creates the user account


if it does not exist and assigns the specified
privileges
If the user account already exists, the GRANT
statement just updates the privileges
425

Revoking Privileges
The syntax for the REVOKE statement is:
REVOKE privilege [(column)] [, privilege [(columns)]] ...
ON {table | * | *.* | database.*}
FROM user;

The REVOKE ALL PRIVILEGES statement


removes all privileges from a user account for a
specified table or database
You must be logged in with the root account or
have sufficient privileges to revoke privileges
from another user account
426

Adding Records
Use the INSERT statement to add individual
records to a table
The syntax for the INSERT statement is:
INSERT INTO table_name (column1, column2, )
VALUES(value1, value2, ...);

The values entered in the VALUES list must


be in the same order in which you defined the
table fields
Specify NULL in any fields for which you do not
have a value
427

Adding Records (continued)


In MySQL Monitor, enter the following code at
the mysql> prompt:
mysql> INSERT INTO company_cars(license,
model_year, make, model, mileage)
VALUES('CK-2987', 2009, 'Toyota',
'Corolla', 3508.4);[ENTER]

428

Adding Records (continued)


The LOAD DATA statement, with the full path
and name of a local text file, is used to add
multiple records to a table
LOAD DATA INFILE 'file_path' INTO TABLE
table_name (column1, column2, );

Each record in the text file must be placed on a


separate line with a tab delimiter between each
field
429

Adding Records (continued)


If the column list is omitted, the values on each
line must be in the same order you defined the
table fields
Use consecutive tabs with nothing between
them to designate a column with no value
In MySQL Monitor, enter the following code at
the mysql> prompt:
mysql> LOAD DATA INFILE 'company_cars.txt'
INTO TABLE company_cars;[ENTER]
430

Adding Records (continued)


The optional FIELDS TERMINATED BY clause
of the LOAD DATA statement allows you to
change the field separator to a character such
as (~ or ,) instead of the default tab
character
In MySQL Monitor, enter the following code at
the mysql> prompt:
mysql> LOAD DATA INFILE 'company_cars.txt
INTO TABLE company_cars;[ENTER]
431

Retrieving Records
Use the SELECT statement to retrieve records
from a table:
SELECT criteria FROM table_name;

Use the asterisk (*) wildcard with the SELECT


statement to retrieve all fields from a table
To return multiple fields, separate field names
with a comma

432

Retrieving Records (continued)


In MySQL Monitor, enter the following code at
the mysql> prompt:
mysql> SELECT model, mileage FROM
company_cars;[ENTER]

433

Using Aggregate Functions


Aggregate functions summarize data in record
sets rather than display the individual records
The COUNT() function is unique in that
The wildcard (*) can be used as a function
argument instead of a field name
The keyword DISTINCT can be used after the
opening parentheses

The DISTINCT keyword can also be used with


the SELECT statement to retrieve records with a
unique value in the WHERE clause
434

Using Aggregate Functions


(continued)
To retrieve aggregate values for groups of
records, use the GROUP BY clause and include
the fields that you use to group the records as
part of the query
In MySQL Monitor, enter the following code at
the mysql> prompt:
mysql> SELECT model_year, AVG(mileage)
FROM company_cars GROUP BY
model_year;[ENTER]
435

Sorting Query Results


Use the ORDER BY keyword with the SELECT
statement to perform an alphanumeric sort of the
results returned from a query
In MySQL Monitor, enter the following code at
the mysql> prompt:
mysql> SELECT make, model FROM inventory
ORDER BY make, model;[ENTER]

436

Sorting Query Results


(continued)
To perform a reverse sort, add the DESC keyword
after the name of the field by which
you want to perform the sort
In MySQL Monitor, enter the following code at
the mysql> prompt:
mysql> SELECT make, model FROM
company_cars ORDER BY make DESC,
model;[ENTER]

437

Filtering Query Results


The criteria portion of the SELECT statement
determines which fields to retrieve from a table
You can also specify which records to return by
using the WHERE keyword
In MySQL Monitor, enter the following code at
the mysql> prompt:
mysql> SELECT * FROM inventory WHERE
make='Martin;[ENTER]

438

Filtering Query Results


(continued)
Use the keywords AND and OR to specify more
detailed conditions about the records you want
to return
In MySQL Monitor, enter the following code
using the AND keyword at the mysql> prompt:
mysql> SELECT * FROM company_cars
WHERE model_year=2007 AND
mileage<60000;[ENTER]

439

Filtering Query Results


(continued)
In MySQL Monitor, enter the following code
using the OR keyword at the mysql> prompt:
mysql> SELECT * FROM company_cars
WHERE make='Toyota OR
make='Honda ORDER BY mileage ;[ENTER]

440

Updating Records
To update records in a table, use the UPDATE
statement
The syntax for the UPDATE statement is:
UPDATE table_name
SET column_name=value
WHERE condition;

The UPDATE keyword specifies the name of the


table to update
The SET keyword specifies the value to assign to
the fields in the records that match the condition
in the WHERE keyword
441

Updating Records (continued)


In MySQL Monitor, enter the following code
using the OR keyword at the mysql> prompt:
mysql> UPDATE company_cars SET mileage=368.2
WHERE make='Ford AND model='Fusion';
[ENTER]

442

Deleting Records
Use the DELETE statement to delete records in a
table
The syntax for the DELETE statement is:
DELETE FROM table_name
WHERE condition;

The DELETE statement deletes all records that


match the condition
To delete all the records in a table, leave off the
WHERE keyword
443

Deleting Records (continued)


In MySQL Monitor, enter the following code at
the mysql> prompt:
mysql> DELETE FROM company_cars WHERE
model_year=2006 AND make='Honda'
AND model='Accord';[ENTER]

To delete all records from a table, omit the


WHERE clause

444

Summary
A database is an ordered collection of
information from which a computer program can
quickly access information
A record in a database is a single, complete set
of related information
Fields are the individual categories of
information stored in a record
A flat-file database stores information in a
single table
445

Summary (continued)
A relational database stores information across
multiple related tables
A query is a structured set of instructions and
criteria for retrieving, adding, modifying, and
deleting database information
Structured query language, or SQL
(pronounced sequel), is a standard data
manipulation language among many database
management systems
446

Summary (continued)
MySQL Monitor is a command-line program that
you use to manipulate MySQL databases
To work with a database, you must first select it
by executing the USE DATEBASE statement
You use the CREATE DATABASE statement to
create a new database
To delete a database, you execute the DROP
DATABASE statement, which removes all tables
from the database and deletes the database itself
447

Summary (continued)
The fields in a table also store data according to
type
To keep your database from growing too large,
you should choose the smallest data type
possible for each field
To create a table, you use the CREATE TABLE
statement, which specifies the table and column
names and the data type for each column

448

Summary (continued)
To modify a table, you use the ALTER TABLE
statement, which specifies the table being
changed and the change to make
To delete a table, you execute the DROP TABLE
statement, which removes all data and the table
definition
You use a GRANT statement to create user
accounts and assign privileges, which refer to
the operations that a user can perform with a
database
449

Summary (continued)
You use the REVOKE statement to take away
privileges from an existing user account for a
specified table or database
You add individual records to a table with the
INSERT statement
To add multiple records to a database, you use
the LOAD DATA statement with a local text file
that contains the records you want to add

450

Summary (continued)
You use the SELECT statement to retrieve
records from a table
You use the ORDER BY keyword with the
SELECT statement to perform an alphanumeric
sort of the results returned from a query
To perform a reverse sort, add the DESC
keyword after the name of the field by which you
want to perform the sort

451

Summary (continued)
You can specify which records to return from a
database by using the WHERE keyword
You use the UPDATE statement to update
records in a table
You use the DELETE statement to delete records
from a table
The phpMyAdmin graphical tool simplifies the
tasks associated with creating and maintaining
databases and tables
452

Chapter 8
Manipulating MySQL
Databases with PHP
2nd Edition

Objectives
In this chapter, you will:
Connect to MySQL from PHP
Work with MySQL databases using PHP
Create, modify, and delete MySQL tables with
PHP
Use PHP to manipulate MySQL records
Use PHP to retrieve database records

454

Connecting to MySQL with PHP


PHP has the ability to access and manipulate
any database that is ODBC compliant
PHP includes functionality that allows you to
work directly with different types of databases,
without going through ODBC
PHP supports SQLite, database abstraction
layer functions, and PEAR DB

455

Determining which MySQL


Package to Use
The mysqli (MySQL Improved) package
became available with PHP 5 and is designed to
work with MySQL version 4.1.3 and later
Earlier versions must use the mysql package
The mysqli package is the object-oriented
equivalent of the mysql package

456

Opening and Closing a MySQL


Connection
Open a connection to a MySQL database server
with the mysql_connect() function
The mysql_connect() function returns a
positive integer if it connects to the database
successfully or FALSE if it does not
Assign the return value from the
mysql_connect() function to a variable that
you can use to access the database in your
script
457

Opening and Closing a MySQL


Connection (continued)
The syntax for the mysql_connect()
function is:
$connection = mysql_connect("host" [,
"user", "password"]);

The host argument specifies the host name


where your MySQL database server is installed
The user and password arguments specify a
MySQL account name and password
458

Opening and Closing a MySQL


Connection (continued)
The database connection is assigned to the
$DBConnect variable
$DBConnect = mysql_connect("localhost",
"dongosselin ", "rosebud");

Close a database connection using the


mysql_close() function
mysql_close($DBConnect);
459

Opening and Closing a MySQL


Connection (continued)

460

Opening and Closing a MySQL


Connection (continued)

Figure 8-1 MySQLInfo.php in a Web browser


461

Reporting MySQL Errors


Reasons for not connecting to a database server
include:
The database server is not running
Insufficient privileges to access the data source
Invalid username and/or password

462

Reporting MySQL Errors


(continued)
The mysql_errno() function returns the error
code from the last attempted MySQL function
call or 0 if no error occurred
The mysql_errno() and mysql_error()
functions return the results of the previous
mysql*() function

463

Suppressing Errors with the Error


Control Operator
By default, functions in the mysql package
display errors and warnings as they occur
Use the error control operator (@) to suppress
error messages
The error control operator can be prepended to
any expression although it is commonly used
with expressions

464

Creating a Database
Use the mysql_create_db() function to
create a new database
The basic syntax for the mysql_create_db()
is:
$result = mysql_create_db( "dbname" [,
connection]);

The mysql_create_db() returns a Boolean


TRUE if successful or FALSE if there was an
error
465

Creating a Database (continued)

Figure 8-2 Error message when the mysql_create_db()


function is unavailable because of insufficient privileges

466

Selecting a Database
The syntax for the mysql_select_db()
function is:
mysql_select_db(database [,
connection]);

The function returns a value of TRUE if it


successfully selects a database or FALSE if it
does not
For security purposes, you may choose to use
an include file to connect to the MySQL server
and select a database
467

Deleting a Database
To delete a database, use the
mysql_drop_db() function.
The format for the mysql_drop_db() function
is:
$Result = mysql_drop_db("dbname" [,
connection]);

The function returns a value of TRUE if it


successfully drops a database or FALSE if it
does not
468

Executing SQL Statements


Use the mysql_query() function to send SQL
statements to MySQL
The syntax for the mysql_query() function is:
mysql_query(query [, connection]);

The mysql_query() function returns one of


three values:
For SQL statements that do not return results
(CREATE DATABASE and CREATE TABLE
statements) it returns a value of TRUE if the
statement executes successfully
469

Executing SQL Statements


(continued)
For SQL statements that return results (SELECT
and SHOW statements) the mysql_query()
function returns a result pointer that represents
the query results
A result pointer is a special type of variable that
refers to the currently selected row in a resultset

The mysql_query() function returns a value of


FALSE for any SQL statements that fail,
regardless of whether they return results

470

Creating and Deleting Tables


Use the CREATE TABLE statement with the
mysql_query() function to create a new table
Use the mysql_select_db() function before
executing the CREATE TABLE statement to
verify that you are in the right database

471

Creating and Deleting Tables


(continued)
$SQLstring = "CREATE TABLE drivers (name
VARCHAR(100), "
. "emp_no SMALLINT, hire_date DATE, "
. "stop_date DATE)";
$QueryResult = @mysql_query($SQLstring, $DBConnect);
if ($QueryResult===FALSE)
echo "<p>Unable to execute the query.</p>"
. "<p>Error code " .
mysql_errno($DBConnect)
. ": " . mysql_error($DBConnect) .
"</p>";
else
echo "<p>Successfully created the table.</p>";
472

Creating and Deleting Tables


(continued)

Figure 8-3 Error code and message that displays when you
attempt to create a table that already exists
473

Creating and Deleting Tables


(continued)
Use the SHOW TABLES LIKE command to
prevent code from trying to create a table that
already exists.
If the table does not exist, the
mysql_num_rows()function will return a value
of 0 rows
$TableName = "subscribers";
$SQLstring = "SHOW TABLES LIKE '$TableName'";
$QueryResult = @mysql_query($SQLstring,
$DBConnect);
474

Creating and Deleting Tables


(continued)
To identify a field as a primary key in MySQL,
include the PRIMARY KEY keywords when you
define a field with the CREATE TABLE
statement
The AUTO_INCREMENT keyword is often used
with a primary key to generate a unique ID for
each new row in a table
The NOT NULL keywords are often used with
primary keys to require that a field include a
value
475

Creating and Deleting Tables


(continued)
To delete a table, use the DROP TABLE
statement with the mysql_query() function

476

Adding, Deleting, and Updating


Records
To add records to a table, use the INSERT and
VALUES keywords with the mysql_query()
function
To add multiple records to a database, use the
LOAD DATA statement with the name of the
local text file containing the records you want to
add
To update records in a table, use the UPDATE
statement
477

Adding, Deleting, and Updating


Records (continued)
The UPDATE keyword specifies the name of the
table to update
The SET keyword specifies the value to assign
to the fields in the records that match the
condition in the WHERE clause
To delete records in a table, use the DELETE
statement with the mysql_query() function
Omit the WHERE clause to delete all records in a
table
478

Retrieving Records into an


Indexed Array
The mysql_fetch_row() function returns the
fields in the current row of a resultset into an
indexed array and moves the result pointer to the
next row
echo "<table width='100% border='1'>";
echo "<tr><th>Make</th><th>Model</th>
<th>Price</th><th>Quantity</th></tr>";
$Row = mysql_fetch_row($QueryResult);
do {
echo "<tr><td>{$Row[0]}</td>";
echo "<td>{$Row[1]}</td>";
echo "<td align='right'>{$Row[2]}</td>";
echo "<td align='right'>{$Row[3]}</td></tr>";
$Row = mysql_fetch_row($QueryResult);
} while ($Row);

479

Using the mysql_affected_rows()


Function
With queries that return results (SELECT
queries), use the mysql_num_rows() function
to find the number of records returned from the
query
With queries that modify tables but do not return
results (INSERT, UPDATE, and DELETE queries),
use the mysql_affected_rows() function to
determine the number of affected rows

480

Using the mysql_affected_rows()


Function (continued)
$SQLstring = "UPDATE company_cars SET mileage=50112.3
WHERE license='AK-1234'";
$QueryResult = @mysql_query($SQLstring, $DBConnect);
if ($QueryResult === FALSE)
echo "<p>Unable to execute the query.</p>"
. "<p>Error code " . mysql_errno($DBConnect)
. ": " . mysql_error($DBConnect) . "</p>";
else
echo "<p>Successfully updated "
. mysql_affected_rows($DBConnect) . "
record(s).</p>";
481

Using the mysql_affected_rows()


Function (continued)

Figure 8-5 Output of mysql_affected_rows() function


for an UPDATE query
482

Using the mysql_info() Function


For queries that add or update records, or alter
a tables structure, use the mysql_info()
function to return information about the query
The mysql_info() function returns the
number of operations for various types of
actions, depending on the type of query
The mysql_info() function returns information
about the last query that was executed on the
database connection
483

Using the mysql_info() Function


(continued)
The mysql_info() function returns information
about queries that match one of the following
formats:

INSERT INTO...SELECT...
INSERT INTO...VALUES (...),(...),(...)
LOAD DATA INFILE ...
ALTER TABLE ...
UPDATE

For any queries that do not match one of these


formats, the mysql_info() function returns an
empty string
484

Using the mysql_info() Function


(continued)
$SQLstring = "INSERT INTO company_cars " .
" (license, model_year, make, model, mileage) " .
" VALUES " .
" ('CPQ-894', 2011, 'Honda', 'Insight', 49.2), " .
" ('CPQ-895', 2011, 'Honda', 'Insight', 17.9), " .
" ('CPQ-896', 2011, 'Honda', 'Insight', 22.6)";
$QueryResult = @mysql_query($SQLstring, $DBConnect);
if ($QueryResult === FALSE)
echo "<p>Unable to execute the query.</p>"
. "<p>Error code " . mysql_errno($DBConnect)
. ": " . mysql_error($DBConnect) . "</p>";
else {
echo "<p>Successfully added the record.</p>";
echo "<p>" . mysql_info($DBConnect) . "</p>";

}
485

Using the mysql_info() Function


(continued)

Figure 8-6 Output of mysql_info() function for an


INSERT query that adds multiple records
486

Using the mysql_info() Function


(continued)
The mysql_info() function also returns
information for LOAD DATA queries
$SQLstring = "LOAD DATA INFILE 'company_cars.txt'
INTO TABLE company_cars;";
$QueryResult = @mysql_query($SQLstring, $DBConnect);
if ($QueryResult === FALSE)
echo "<p>Unable to execute the query.</p>"
. "<p>Error code " . mysql_errno($DBConnect)
. ": " . mysql_error($DBConnect) . "</p>";
else {
echo "<p>Successfully added the record.</p>";
echo "<p>" . mysql_info($DBConnect) . "</p>";
}
487

Using the mysql_info() Function


(continued)

Figure 8-7 Output of mysql_info() function for a


LOAD DATA query
488

Working with Query Results

489

Retrieving Records into an Indexed


Array
The mysql_fetch_row() function returns the
fields in the current row of a result set into an
indexed array and moves the result pointer to
the next row

490

Retrieving Records into an Indexed


Array
$SQLstring = "SELECT * FROM company_cars";
$QueryResult = @mysql_query($SQLstring, $DBConnect);
echo "<table width='100%' border='1'>\n";
echo "<tr><th>License</th><th>Make</th><th>Model</th>
<th>Mileage</th><th>Year</th></tr>\n";
while (($Row = mysql_fetch_row($QueryResult)) !== FALSE) {
echo "<tr><td>{$Row[0]}</td>";
echo "<td>{$Row[1]}</td>";
echo "<td>{$Row[2]}</td>";
echo "<td align='right'>{$Row[3]}</td>";
echo "<td>{$Row[4]}</td></tr>\n";
}
echo "</table>\n";
491

Retrieving Records into an Indexed


Array

Figure 8-8 Output of the company_cars table in a Web Browser


492

Retrieving Records into an


Associative Array
The mysql_fetch_assoc() function returns
the fields in the current row of a resultset into an
associative array and moves the result pointer to
the next row
The difference between
mysql_fetch_assoc() and
mysql_fetch_row() is that instead of
returning the fields into an indexed array, the
mysql_fetch_assoc() function returns the
fields into an associate array and uses each field
name as the array key
493

Closing Query Results


When you are finished working with query
results retrieved with the mysql_query()
function, use the mysql_free_result()
function to close the resultset
To close the resultset, pass to the
mysql_free_result() function the
variable containing the result pointer from the
mysql_query() function

494

Accessing Query Result


Information
The mysql_num_rows() function returns the
number of rows in a query result
The mysql_num_fields() function returns the
number of fields in a query result
Both functions accept a database connection
variable as an argument

495

Accessing Query Result


Information (continued)
$SQLstring = "SELECT * FROM company_cars";
$QueryResult = @mysql_query($SQLstring, $DBConnect);
if ($QueryResult === FALSE)
echo "<p>Unable to execute the query.</p>"
. "<p>Error code " . mysql_errno($DBConnect)
. ": " . mysql_error($DBConnect) . "</p>";
else
echo "<p>Successfully executed the query.</p>";
$NumRows = mysql_num_rows($QueryResult);
$NumFields = mysql_num_fields($QueryResult);
if ($NumRows != 0 && $NumFields != 0)
echo "<p>Your query returned " .
mysql_num_rows($QueryResult) . " rows and "
. mysql_num_fields($QueryResult) . " fields.</p>";
else
echo "<p>Your query returned no results.</p>";
mysql_close($DBConnect);

496

Accessing Query Result


Information (continued)

Figure 8-10 Output of the number of rows and fields


returned from a query
497

Summary
The mysql_connect() function opens a
connection to a MySQL database server
The mysql_close() function closes a
database connection
The mysql_errno() function returns the error
code from the last attempted MySQL function
call or zero if no error occurred

498

Summary (continued)
The mysql_error() function returns the error
message from the last attempted MySQL function
call or an empty string if no error occurred
The error control operator (@) suppresses
error messages
You use the mysql_create_db() function to
create a new database
The mysql_select_db() function selects a
database
499

Summary (continued)
You use the mysql_drop_db() function to
delete a database
The mysql_query() function sends SQL
statements to MySQL
A result pointer is a special type of variable that
refers to the currently selected row in a resultset
You use the CREATE TABLE statement with the
mysql_query() function to create a table
500

Summary (continued)
The PRIMARY KEY clause indicates a field or
fields that will be used as a referential index for
the table
The AUTO_INCREMENT clause creates a field that
is automatically updated with the next sequential
value for that column
The NOT NULL clause creates a field that must
contain data
You use the DROP TABLE statement with the
mysql_query() function to delete a table
501

Summary (continued)
You use the LOAD DATA statement and the
mysql_query() function with a local text file
to add multiple records to a database
You use the UPDATE statement with the
mysql_query() function to update records in
a table
You use the DELETE statement with the
mysql_query() function to delete records from
a table
502

Summary (continued)
The mysql_info() function returns the
number of operations for various types of
actions, depending on the type of query.
The mysql_fetch_row() function returns the
fields in the current row of a resultset into an
indexed array and moves the result pointer to
the next row.

503

Summary (continued)
The mysql_fetch_assoc() function returns
the fields in the current row of a resultset into an
associative array and moves the result pointer to
the next row
The mysql_free_result() function closes a
resultset

504

Summary (continued)
The mysql_num_rows() function returns the
number of rows in a query result, and the
mysql_num_fields() function returns the
number of fields in a query result
With queries that return results, such as SELECT
queries, you can use the mysql_num_rows()
function to find the number of records returned
from the query

505

Chapter 9
Managing State Information
2nd Edition

Objectives
In this chapter, you will:
Learn about state information
Use hidden form fields to save state information
Use query strings to save state information
Use cookies to save state information
Use sessions to save state information

507

Understanding State
Information
Information about individual visits to a Web site
is called state information
HTTP was originally designed to be stateless
Web browsers store no persistent data about a
visit to a Web site
Maintaining state means to store persistent
information about Web site visits with hidden
form fields, query strings, cookies, and sessions

508

Understanding State
Information (continued)
Customize individual Web pages based on user
preferences
Temporarily store information for a user as a
browser navigates within a multipart form
Allow a user to create bookmarks for returning
to specific locations within a Web site
Provide shopping carts that store order
information

509

Understanding State
Information (continued)
Store user IDs and passwords
Use counters to keep track of how many times
a user has visited a site
The four tools for maintaining state information
with PHP are:

Hidden form fields


Query strings
Cookies
Sessions
510

Understanding State
Information (continued)

Figure 9-1 College Internship Available Opportunities


Web site page flow
511

Understanding State
Information (continued)

Figure 9-2 Registration/Log In Web page


512

Understanding State
Information (continued)

Figure 9-3 New Intern Registration Web page


after successful registration
513

Understanding State
Information (continued)

Figure 9-4 Verify Login Web Page for a successful login


514

Understanding State
Information (continued)

Figure 9-5 The Available Opportunities Web page


with the Intern information at top of screen
515

Using Hidden Form Fields to


Save State Information
Create hidden form fields with the <input>
element
Hidden form fields temporarily store data that
needs to be sent to a server that a user does not
need to see
Examples include the result of a calculation
The syntax for creating hidden form fields is:
<input type="hidden">

516

Using Hidden Form Fields to


Save State Information
(continued)

Hidden form field attributes are name and value


When submitting a form to a PHP script,
access the values submitted from the form with
the $_GET[] and $_POST[] autoglobals
To pass form values from one PHP script to
another PHP script, store the values in hidden
form fields

517

Using Hidden Form Fields to


Save State Information
(continued)
echo "<form method='post' " .
" action='AvailableOpportunities.php'>\n";
echo "<input type='hidden' name='internID' " .
" value='$InternID'>\n";
echo "<input type='submit' name='submit' " .
" value='View Available Opportunities'>\n";
echo "</form>\n";

518

Using Query Strings to Save


State Information
A query string is a set of name=value pairs
appended to a target URL
Consists of a single text string containing one or
more pieces of information
Add a question mark (?) immediately after the
URL followed by the query string that contains
the information you want to preserve in
name/value pairs

519

Using Query Strings to Save


State Information (continued)
Separate individual name=value pairs within the
query string using ampersands (&)
A question mark (?) and a query string are
automatically appended to the URL of a serverside script for any forms that are submitted with
the GET method
<a href="http://www.example.com/TargetPage
.php?firstName=Don&lastName=Gosselin&
occupation=writer">Link Text</a>

520

Using Query Strings to Save


State Information (continued)
echo "{$_GET['firstName']} {$_GET['lastName']}
is a {$_GET['occupation']}. ";

Figure 9-6 Output of the contents of a query string


521

Using Cookies to Save State


Information
Query strings do not permanently maintain
state information
After a Web page that reads a query string
closes, the query string is lost
To store state information beyond the current
Web page session, Netscape created cookies
Cookies, or magic cookies, are small pieces of
information about a user that are stored by a
Web server in text files on the users computer
522

Using Cookies to Save State


Information (continued)
Temporary cookies remain available only for the
current browser session
Persistent cookies remain available beyond the
current browser session and are stored in a text
file on a client computer
Each individual server or domain can store
between 20 and 70 cookies on a users computer
Total cookies per browser cannot exceed 300
The largest cookie size is 4 kilobytes
523

Creating Cookies
The syntax for the setcookie() function is:
setcookie(name [,value ,expires, path, domain, secure])

You must pass each of the arguments in the


order specified in the syntax
To skip the value, path, and domain
arguments, specify an empty string as the
argument value
To skip the expires and secure arguments,
specify 0 as the argument value

524

Creating Cookies (continued)


Call the setcookie() function before sending
the Web browser any output, including white
space, HTML elements, or output from the
echo() or print() statements
Users can choose whether to accept cookies
that a script attempts to write to their system
A value of TRUE is returned even if a user rejects
the cookie

525

Creating Cookies (continued)


Cookies cannot include semicolons or other
special characters, such as commas or spaces,
that are transmitted between Web browsers and
Web servers using HTTP
Cookies can include special characters when
created with PHP since encoding converts
special characters in a text string to their
corresponding hexadecimal ASCII value

526

The name and value


Arguments

Cookies created with only the name and value


arguments of the setcookie() function are
temporary cookies because they are available for
only the current browser session
<?php
setcookie("firstName", "Don");
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>College Internships</title>
...
527

The name and value


Arguments (continued)
The setcookie() function can be called
multiple times to create additional cookies as
long as the setcookie() statements come
before any other output on a Web page
setcookie("firstName", "Don");
setcookie("lastName", "Gosselin");
setcookie("occupation", "writer");

528

The name and value


Arguments (continued)
The following code creates an indexed cookie
array named professional[] that contains
three cookie values:
setcookie("firstName", "Don");
setcookie("lastName", "Gosselin");
setcookie("occupation", "writer");

529

The name and value


Arguments (continued)
The following code creates an associative
cookie array named professional[] that
contains three cookie values:
setcookie("professional['firstName']", "Don");
setcookie("professional['lastName']", "Gosselin");
setcookie("professional['occupation']", "writer");

530

The expires Argument


The expires argument determines how long a
cookie can remain on a client system before it is
deleted
Cookies created without an expires argument
are available for only the current browser
session
To specify a cookies expiration time, use PHPs
time() function
setcookie("firstName", "Don", time()+3600);

531

The path Argument


The path argument determines the availability
of a cookie to other Web pages on a server
Using the path argument allows cookies to be
shared across a server
A cookie is available to all Web pages in a
specified path as well as all subdirectories in the
specified path
setcookie("firstName", "Don", time()+3600, "/marketing/");

532

The domain Argument


The domain argument is used for sharing
cookies across multiple servers in the same
domain
Cookies cannot be shared outside of a domain
setcookie("firstName", "Don, time()+3600, "/", ".gosselin.com");

533

The secure Argument


The secure argument indicates that a cookie
can only be transmitted across a secure Internet
connection using HTTPS or another security
protocol
To use this argument, assign a value of 1 (for
TRUE) or 0 (for FALSE) as the last argument of
the setcookie() function
setcookie("firstName, "Don", time()+3600, "/", ".gosselin.com", 1);

534

Reading Cookies
Cookies that are available to the current Web
page are automatically assigned to the
$_COOKIE autoglobal
Access each cookie by using the cookie name
as a key in the associative $_COOKIE[] array
echo $_COOKIE['firstName'];

Newly created cookies are not available until


after the current Web page is reloaded

535

Reading Cookies (continued)


To ensure that a cookie is set before you attempt
to use it, use the isset() function
setcookie("firstName", "Don");
setcookie("lastName", "Gosselin");
setcookie("occupation", "writer");
if (isset($_COOKIE['firstName'])
&& isset($_COOKIE['lastName'])
&& isset($_COOKIE['occupation']))
echo "{$_COOKIE['firstName']} {$_COOKIE['lastName']}
is a {$_COOKIE['occupation']}.";

536

Reading Cookies (continued)


Use multidimensional array syntax to read
each cookie value
setcookie("professional[0]", "Don");
setcookie("professional[1]", "Gosselin");
setcookie("professional[2]", "writer");
if (isset($_COOKIE['professional']))
echo "{$_COOKIE['professional'][0]}
{$_COOKIE['professional'][1]} is a
{$_COOKIE['professional'][2]}.";

537

Deleting Cookies
To delete a persistent cookie before the time
assigned to the expires argument elapses,
assign a new expiration value that is sometime
in the past
Do this by subtracting any number of seconds
from the time() function
setcookie("firstName", "", time()-3600);
setcookie("lastName", "", time()-3600);
setcookie("occupation", "", time()-3600);
538

Using Sessions to Save State


Information
Spyware gathers user information from a local
computer for marketing and advertising
purposes without the users knowledge
A session refers to a period of activity when a
PHP script stores state information on a Web
server
Sessions allow you to maintain state information
even when clients disable cookies in their Web
browsers
539

Starting a Session
The session_start() function starts a new
session or continues an existing one
The session_start() function generates a
unique session ID to identify the session
A session ID is a random alphanumeric string
that looks something like:
7f39d7dd020773f115d753c71290e11f

The session_start() function creates a text


file on the Web server that is the same name as
the session ID, preceded by sess_
540

Starting a Session (continued)


Session ID text files are stored in the Web
server directory specified by the
session.save_path directive in your php.ini
configuration file
The session_start() function does not
accept any arguments, nor does it return a value
that you can use in your script
<?php
session_start();
...
541

Starting a Session (continued)


You must call the session_start() function
before you send the Web browser any output
If a clients Web browser is configured to accept
cookies, the session ID is assigned to a
temporary cookie named PHPSESSID
Pass the session ID as a query string or hidden
form field to any Web pages that are called as
part of the current session

542

Starting a Session (continued)


<?php
session_start();
...
?>
<p><a href='<?php echo "Occupation.php?PHPSESSID="
. session_id() ?>'>Occupation</a></p>

543

Working with Session Variables


Session state information is stored in the
$_SESSION autoglobal
When the session_start() function is called,
PHP either initializes a new $_SESSION
autoglobal or retrieves any variables for the
current session (based on the session ID) into
the $_SESSION autoglobal

544

Working with Session Variables


(continued)
<?php
session_start();
$_SESSION['firstName'] = "Don";
$_SESSION['lastName'] = "Gosselin";
$_SESSION['occupation'] = "writer";
?>
<p><a href='<?php echo "Occupation.php?"
. session_id() ?>'>Occupation</a></p>

545

Working with Session Variables


(continued)
Use the isset() function to ensure that a
session variable is set before you attempt to
use it
<?php
session_start();
if (isset($_SESSION['firstName']) &&
isset($_SESSION['lastName'])
&& isset($_SESSION['occupation']))
echo "<p>" . $_SESSION['firstName'] . " "
. $_SESSION['lastName'] . " is a "
. $_SESSION['occupation'] . "</p>";
?>
546

Deleting a Session
To delete a session manually, perform the
following steps:
1. Execute the session_start() function
2. Use the array() construct to reinitialize the
$_SESSION autoglobal
3. Use the session_destroy() function to
delete the session

547

Deleting a Session (continued)


<?php
session_start();
$_SESSION = array();
session_destroy();
?>

548

Summary
Information about individual visits to a Web site
is called state information. Maintaining state
means to store persistent information about Web
site visits
To pass form values from one PHP script to
another, you can store the values in hidden
form fields, which are submitted along with
other types of form fields

549

Summary (continued)
One way to preserve information following a
users visit to a Web page is to append a query
string to the end of a URL. To pass information
from one Web page to another using a query
string, add a question mark (?) immediately after
a URL, followed by the query string containing
the information you want to preserve in
name/value pairs.

550

Summary (continued)
Cookies, also called magic cookies, are small
pieces of information about a user that are
stored by a Web server in text files on the users
computer. Cookies can be temporary or
persistent.
Temporary cookies remain available only for the
current browser session
Persistent cookies remain available beyond the
current browser session and are stored in a text
file on a client computer
551

Summary (continued)
You use the setcookie() function to create
cookies in PHP. You must call the setcookie()
function before you send the Web browser any
output, including white space, HTML elements,
or output from the echo or print statements.
Cookies created with only the name and value
arguments of the setcookie() function are
temporary cookies, because they are available
for only the current browser session
552

Summary (continued)
For a cookie to persist beyond the current
browser session, you must use the expires
argument with the setcookie() function
The path argument of the setcookie()
function determines the availability of a cookie to
other Web pages on a server
The secure argument of the setcookie()
function indicates that a cookie can only be
transmitted across a secure Internet connection
using HTTPS or another security protocol
553

Summary (continued)
To delete a persistent cookie before the time
elapses in the assigned expires argument,
assign a new expiration value to a time in the
past and clearing the value. You do this by
subtracting any number of seconds from the
time() function and setting the value of the
cookie to the empty string.

554

Summary (continued)
Sessions refer to periods of activity when a PHP
script stores state information on a Web server.
When you start a new session, the
session_start() function generates a unique
session ID to identify the session. If a clients
Web browser is configured to accept cookies,
the session ID is assigned to a temporary cookie
named PHPSESSID.

555

Summary (continued)
You must call the session_start() function
before you send the Web browser any output,
including white space, HTML elements, or output
from the echo or print statements
You store session state information in the
$_SESSION[] autoglobal

556

Summary (continued)
To delete a session, execute the
session_start() function, use the array[]
construct to reinitialize the $_SESSION[]
autoglobal and call the session_destroy()
function

557

Potrebbero piacerti anche