Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
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
Understanding Functions
A function is a subroutine (or individual statements
12
14
17
18
19
20
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;
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
24
Displaying Variables
25
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);
29
30
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
35
=
=
=
=
=
=
=
=
=
=
40
41
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)
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
46
47
Arithmetic Operators
Arithmetic operators are used in PHP to
perform mathematical calculations (+ - x )
48
51
52
53
54
56
Assignment Operators
Assignment operators are used for assigning
a value to a variable:
$MyFavoriteSuperHero = "Superman";
$MyFavoriteSuperHero = "Batman";
57
58
60
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;
65
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
Calling Functions
function displayCompanyName($CompanyName) {
echo "<p>$CompanyName</p>";
}
displayCompanyName("Course Technology");
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
84
86
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
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
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
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);
}
102
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);
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
111
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>";
}
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
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
126
127
128
129
131
Figure 3-4 Output of literal text containing double quotation escape sequences
132
134
in
a
String
The most commonly used string counting
135
in
a
String
(continued)
The str_word_count() function returns the
136
141
145
147
148
151
154
156
157
158
159
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
162
163
164
165
166
168
169
170
171
173
175
176
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
185
187
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
204
207
208
214
216
218
219
220
221
224
225
226
229
Header
Button Navigation
Dynamic Content
Footer
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
245
247
248
249
251
252
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
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
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
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)
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
263
264
265
266
$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
269
270
271
$_FILES['picture_file']['tmp_name'] //
Contains the temporary location of the
file contents
273
274
275
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
Downloading Files
(continued)
279
280
281
282
283
284
285
$SFWeather = file_get_contents("sfweather.txt");
echo $SFWeather;
286
287
289
293
296
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
300
Copying
Moving
Renaming
Deleting
301
303
304
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)
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)
325
Manipulating Elements
(continued)
328
331
332
334
335
336
338
342
344
346
348
349
Sorting Arrays
The most commonly used array sorting
functions are:
sort() and rsort() for indexed arrays
ksort() and krsort() for associative arrays
351
352
353
354
Figure 6-12 Output of an array after applying the sort() and rsort() functions
355
Figure 6-13 Output of an associative array after sorting with the sort() function
356
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
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, ...);
363
364
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)
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
374
375
377
378
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)
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)
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)
One-to-Many Relationship
(continued)
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
401
403
Logging in to MySQL
Enter the following command:
mysql h host u user p
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>
Logging in to MySQL
(continued)
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
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
410
Creating Databases
Use the CREATE DATABASE statement to create
a new database:
mysql> CREATE DATABASE vehicle_fleet;[ENTER]
411
Selecting a Database
Use the DATABASE() function to return the
name of the currently active database
mysql> SELECT DATABASE();[ENTER]
413
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
416
417
418
Renaming Columns
Use the ALTER TABLE to rename columns using the
following syntax
ALTER TABLE table_name MODIFY [COLUMN] column_name
column_type;
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;
422
423
424
Granting Privileges
The syntax for the GRANT statement is:
GRANT privilege [(column)] [, privilege [(columns)]] ...
ON {table | * | *.* | database.*}
TO user [IDENTIFIED BY 'password'];
Revoking Privileges
The syntax for the REVOKE statement is:
REVOKE privilege [(column)] [, privilege [(columns)]] ...
ON {table | * | *.* | database.*}
FROM user;
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, ...);
428
Retrieving Records
Use the SELECT statement to retrieve records
from a table:
SELECT criteria FROM table_name;
432
433
436
437
438
439
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;
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;
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
455
456
460
462
463
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]);
466
Selecting a Database
The syntax for the mysql_select_db()
function is:
mysql_select_db(database [,
connection]);
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]);
470
471
Figure 8-3 Error code and message that displays when you
attempt to create a table that already exists
473
476
479
480
INSERT INTO...SELECT...
INSERT INTO...VALUES (...),(...),(...)
LOAD DATA INFILE ...
ALTER TABLE ...
UPDATE
}
485
489
490
494
495
496
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:
Understanding State
Information (continued)
Understanding State
Information (continued)
Understanding State
Information (continued)
Understanding State
Information (continued)
Understanding State
Information (continued)
516
517
518
519
520
Creating Cookies
The syntax for the setcookie() function is:
setcookie(name [,value ,expires, path, domain, secure])
524
525
526
528
529
530
531
532
533
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'];
535
536
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
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
542
543
544
545
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
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