chapter 1 getting started with php php programming with mysql

608
Chapter 1 Getting Started with PHP PHP Programming with MySQL

Upload: nora-sanders

Post on 13-Jan-2016

275 views

Category:

Documents


2 download

TRANSCRIPT

Chapter 1

Getting Started with PHP

PHP Programming with MySQL

2PHP Programming with MySQL

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

3PHP Programming with MySQL

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 client’s Web browser; only the output of the processing is sent to the browser

4PHP Programming with MySQL

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

5PHP Programming with MySQL

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

6PHP Programming with MySQL

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

7PHP Programming with MySQL

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

8PHP Programming with MySQL

Short PHP Script Delimiters

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

• Short delimiters can be disabled in a Web server’s 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

9PHP Programming with MySQL

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

10PHP Programming with MySQL

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

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

11PHP Programming with MySQL

12PHP Programming with MySQL

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

13PHP Programming with MySQL

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>

14PHP Programming with MySQL

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>

15PHP Programming with MySQL

Creating Multiple Code Declaration Blocks (continued)

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

16PHP Programming with MySQL

Creating Multiple Code Declaration Blocks (continued)

Figure 1-10 PHP Environment Information Web page

17PHP Programming with MySQL

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>";

?>

18PHP Programming with MySQL

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

19PHP Programming with MySQL

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

20PHP Programming with MySQL

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

followcode 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. */?>

21PHP Programming with MySQL

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

22PHP Programming with MySQL

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>";

23PHP Programming with MySQL

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

24PHP Programming with MySQL

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;

25PHP Programming with MySQL

Displaying Variables

Figure 1-11 Output from an echo statement that is passed text and a variable

26PHP Programming with MySQL

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

27PHP Programming with MySQL

Modifying Variables

• You can modify a variable’s 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>";

28PHP Programming with MySQL

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

29PHP Programming with MySQL

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

30PHP Programming with MySQL

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

31PHP Programming with MySQL

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

32PHP Programming with MySQL

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)

33PHP Programming with MySQL

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

34PHP Programming with MySQL

Arrays

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

Figure 1-17 Conceptual example of an array

35PHP Programming with MySQL

Declaring and Initializing Indexed Arrays

• An element refers to each piece of data that is stored within an array

• An index is an element’s 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]

36PHP Programming with MySQL

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" );

37PHP Programming with MySQL

Declaring and Initializing Indexed Arrays (continued)

• Array name and brackets syntax is:$array_name[ ]

$Provinces[] = "Newfoundland and Labrador"; $Provinces[] = "Prince Edward Island"; $Provinces[] = "Nova Scotia"; $Provinces[] = "New Brunswick"; $Provinces[] = "Quebec"; $Provinces[] = "Ontario"; $Provinces[] = "Manitoba"; $Provinces[] = "Saskatchewan"; $Provinces[] = "Alberta"; $Provinces[] = "British Columbia";

38PHP Programming with MySQL

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

39PHP Programming with MySQL

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>";

40PHP Programming with MySQL

Accessing Element Information (continued)

Figure 1-19 Output of the count() function

41PHP Programming with MySQL

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

42PHP Programming with MySQL

Accessing Element Information (continued)

Figure 1-21 Output of the $Provinces[ ] array with the print_r() function

43PHP Programming with MySQL

Modifying Elements

• To modify an array element. include the index for an individual element of the array:$HospitalDepts = array(

"Anesthesia", // first element(0)"Molecular Biology", // second element

(1)"Neurology"); // third element (2)

To change the first array element in the $HospitalDepts[] array from “Anesthesia” to “Anesthesiology” use:

$HospitalDepts[0] = "Anesthesiology";

44PHP Programming with MySQL

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";

45PHP Programming with MySQL

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

46PHP Programming with MySQL

Building Expressions (continued)

47PHP Programming with MySQL

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

48PHP Programming with MySQL

Arithmetic Operators

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

49PHP Programming with MySQL

Arithmetic Operators (continued)

Figure 1-22 Results of arithmetic expressions

50PHP Programming with MySQL

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

51PHP Programming with MySQL

Arithmetic Binary Operators

52PHP Programming with MySQL

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

53PHP Programming with MySQL

Arithmetic Unary Operators (continued)

Figure 1-24 Script that uses the prefix increment operator

54PHP Programming with MySQL

Arithmetic Unary Operators (continued)

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

55PHP Programming with MySQL

Arithmetic Unary Operators (continued)

Figure 1-26 Script that uses the postfix increment operator

56PHP Programming with MySQL

Arithmetic Unary Operators (continued)

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

57PHP Programming with MySQL

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

58PHP Programming with MySQL

Assignment Operators (continued)

59PHP Programming with MySQL

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

60PHP Programming with MySQL

Comparison and Conditional Operators (continued)

61PHP Programming with MySQL

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

62PHP Programming with MySQL

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

63PHP Programming with MySQL

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

64PHP Programming with MySQL

Special Operators

65PHP Programming with MySQL

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

66PHP Programming with MySQL

Type Casting (continued)

• Returns one of the following strings, depending on the data type:– Boolean– Integer– Double– String– Array– Object– Resource– NULL– Unknown type

67PHP Programming with MySQL

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

68PHP Programming with MySQL

Understanding Operator Precedence (continued)

69PHP Programming with MySQL

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

70PHP Programming with MySQL

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

71PHP Programming with MySQL

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

72PHP Programming with MySQL

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

73PHP Programming with MySQL

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.

74PHP Programming with MySQL

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

75PHP Programming with MySQL

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

76PHP Programming with MySQL

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

Chapter 2

Functions and ControlStructures

PHP Programming with MySQL

PHP Programming with MySQL

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

PHP Programming with MySQL

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

PHP Programming with MySQL

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

PHP Programming with MySQL

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

PHP Programming with MySQL

Calling Functions

function displayCompanyName($CompanyName) {

echo "<p>$CompanyName</p>";

}

displayCompanyName("Course Technology");

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

82

PHP Programming with MySQL

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

PHP Programming with MySQL

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

PHP Programming with MySQL

Understanding Variable Scope

• Variable scope is where in your program a declared variable can be used

• A variable’s 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

PHP Programming with MySQL

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

PHP Programming with MySQL

The global Keyword (continued)

<?php

$GlobalVariable = "Global variable";

function scopeExample() {

global $GlobalVariable;

echo "<p>$GlobalVariable</p>";

}

scopeExample();

?>

87

PHP Programming with MySQL

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

PHP Programming with MySQL

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

PHP Programming with MySQL

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

PHP Programming with MySQL

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

PHP Programming with MySQL

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

PHP Programming with MySQL

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

PHP Programming with MySQL

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

PHP Programming with MySQL

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 statement’s expression

95

PHP Programming with MySQL

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

PHP Programming with MySQL

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

PHP Programming with MySQL

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

PHP Programming with MySQL

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

PHP Programming with MySQL

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

PHP Programming with MySQL

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

PHP Programming with MySQL

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

PHP Programming with MySQL

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

PHP Programming with MySQL

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

PHP Programming with MySQL

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

PHP Programming with MySQL

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

PHP Programming with MySQL

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

PHP Programming with MySQL

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

PHP Programming with MySQL

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

PHP Programming with MySQL

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

PHP Programming with MySQL

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

PHP Programming with MySQL

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

PHP Programming with MySQL

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

PHP Programming with MySQL

foreach Statements (continued)

$DaysOfWeek = array(("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday");

foreach ($DaysOfWeek as $Day) {

echo "<p>$Day</p>";

}

114

PHP Programming with MySQL

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

PHP Programming with MySQL

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

PHP Programming with MySQL

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

PHP Programming with MySQL

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

PHP Programming with MySQL

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

PHP Programming with MySQL

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

PHP Programming with MySQL

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

PHP Programming with MySQL

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

PHP Programming with MySQL

124PHP Programming with MySQL

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

125PHP Programming with MySQL

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 variableecho "<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)

126PHP Programming with MySQL

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

127PHP Programming with MySQL

Constructing Text Strings (continued)

$LatinQuote = '<p>"Et tu, Brute!"</p>';

echo $LatinQuote;

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

128PHP Programming with MySQL

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;

129PHP Programming with MySQL

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;

130PHP Programming with MySQL

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>";

131PHP Programming with MySQL

Adding Escape Characters and Sequences (continued)

• The escape character combined with one or more other characters is an escape sequence

132PHP Programming with MySQL

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

133PHP Programming with MySQL

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>";

134PHP Programming with MySQL

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

135PHP Programming with MySQL

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>";

136PHP Programming with MySQL

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>";

137PHP Programming with MySQL

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

138PHP Programming with MySQL

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

139PHP Programming with MySQL

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

140PHP Programming with MySQL

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;'

141PHP Programming with MySQL

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

142PHP Programming with MySQL

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

143PHP Programming with MySQL

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

144PHP Programming with MySQL

• 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

Other Ways to Manipulate a String (continued)

145PHP Programming with MySQL

• 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

Other Ways to Manipulate a String

(continued)

146PHP Programming with MySQL

Other Ways to Manipulate a String

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

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

147PHP Programming with MySQL

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

148PHP Programming with MySQL

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

149PHP Programming with MySQL

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

150PHP Programming with MySQL

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

151PHP Programming with MySQL

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 = "[email protected]";

$NewEmail = str_replace("president", "vice.president", $Email);

echo $NewEmail; // prints '[email protected]'

152PHP Programming with MySQL

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

153PHP Programming with MySQL

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

154PHP Programming with MySQL

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

155PHP Programming with MySQL

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

156PHP Programming with MySQL

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

157PHP Programming with MySQL

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

158PHP Programming with MySQL

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

159PHP Programming with MySQL

Converting between Strings and Arrays (continued)

• The implode()function combines an array’s elements into a single string, separated by specified characters

• The syntax is:$variable = implode(separators, array);

160PHP Programming with MySQL

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

161PHP Programming with MySQL

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>";

162PHP Programming with MySQL

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”)

163PHP Programming with MySQL

String Comparison Functions

• The strcasecmp() function performs a case-insensitive comparison of strings

• The strcmp() function performs a case-sensitive 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

164PHP Programming with MySQL

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

165PHP Programming with MySQL

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>";

166PHP Programming with MySQL

Determining the Similarity of Two Strings (continued)

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

167PHP Programming with MySQL

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 name’s phonetic equivalent

• The metaphone() function returns a code representing an English word’s approximate sound

168PHP Programming with MySQL

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>";

169PHP Programming with MySQL

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

170PHP Programming with MySQL

Working with Regular Expressions(continued)

171PHP Programming with MySQL

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);

172PHP Programming with MySQL

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 pattern-matching rules

• Regular expression patterns are enclosed in opening and closing delimiters– The most common character delimiter is the

forward slash (/)

173PHP Programming with MySQL

Writing Regular Expression Patterns

(continued)

174PHP Programming with MySQL

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

175PHP Programming with MySQL

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

176PHP Programming with MySQL

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

177PHP Programming with MySQL

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

178PHP Programming with MySQL

Specifying Quantity

• Metacharacters that specify the quantity of a match are called quantifiers

179PHP Programming with MySQL

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

180PHP Programming with MySQL

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

181PHP Programming with MySQL

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

182PHP Programming with MySQL

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

183PHP Programming with MySQL

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})$/

184PHP Programming with MySQL

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

185PHP Programming with MySQL

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

186PHP Programming with MySQL

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

187PHP Programming with MySQL

Defining Character Classes(continued)

188PHP Programming with MySQL

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

189PHP Programming with MySQL

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

190PHP Programming with MySQL

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

191PHP Programming with MySQL

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

192PHP Programming with MySQL

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

193PHP Programming with MySQL

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

194PHP Programming with MySQL

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 array’s elements into a single string, separated by specified characters

195PHP Programming with MySQL

Summary (continued)

• The strcasecmp() function performs a case-insensitive 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

196PHP Programming with MySQL

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 pattern-matching rules

• In a regular expression, a backslash character (\) is used to match metacharacters as literal values

197PHP Programming with MySQL

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

198PHP Programming with MySQL

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

Chapter 4

Handling User Input

PHP Programming with MySQL

200PHP Programming with MySQL

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

201PHP Programming with MySQL

Using Autoglobals

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

202PHP Programming with MySQL

Using Autoglobals (continued)

• Autoglobals are associative arrays– To access the values in an associative array,

place the element’s 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

203PHP Programming with MySQL

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

204PHP Programming with MySQL

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">

205PHP Programming with MySQL

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 form’s 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

206PHP Programming with MySQL

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

207PHP Programming with MySQL

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

208PHP Programming with MySQL

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 (+)

209PHP Programming with MySQL

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 character’s ASCII value

• (the following code shows three form elements submitted to the process_Scholarship.php script)

http://www.example.net/process_Scholarship.php?fName=John&lName=Smith&Submit=Send+Form

210PHP Programming with MySQL

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

211PHP Programming with MySQL

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

212PHP Programming with MySQL

Retrieving Submitted Data

• The PHP script that processes the user-submitted 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 . ".";

213PHP Programming with MySQL

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

Handling Special Characters(continued)

214PHP Programming with MySQL

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)

215PHP Programming with MySQL

216PHP Programming with MySQL

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

217PHP Programming with MySQL

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

218PHP Programming with MySQL

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

219PHP Programming with MySQL

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

220PHP Programming with MySQL

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

221PHP Programming with MySQL

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

222PHP Programming with MySQL

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>

223PHP Programming with MySQL

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: [email protected]– Recipients name and e-mail address: Mary Smith <[email protected]>

224PHP Programming with MySQL

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.

225PHP Programming with MySQL

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 elementDate: Fri, 03 Apr 2009 16:05:50 -0400

From: Linda M. Jones [email protected]: Mary R. Jones <[email protected]>

• A successful e-mail message returns a value of TRUE

226PHP Programming with MySQL

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, it’s often easier to use an All-in-One form—a single script used display a Web form and process its data

227PHP Programming with MySQL

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 setif (isset($Submit)) {

// Validate the data

}

– The argument of the isset() function is the name assigned to the Submit button in the Web form

228PHP Programming with MySQL

Redisplaying the Web Form

• If the submitted data did not pass all validation checks or no data has been entered, the All-in-One form will display the Web form, for the user to enter data for the first time or re-enter data that did not pass validationif (isset ($_POST['Submit'])) {

// Process the data

}

else {

// Display the Web form

}

229PHP Programming with MySQL

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

230PHP Programming with MySQL

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

231PHP Programming with MySQL

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>

232PHP Programming with MySQL

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”

233PHP Programming with MySQL

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

234PHP Programming with MySQL

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;

}

}

235PHP Programming with MySQL

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

236PHP Programming with MySQL

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

237PHP Programming with MySQL

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

238PHP Programming with MySQL

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

239PHP Programming with MySQL

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

240PHP Programming with MySQL

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

241PHP Programming with MySQL

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)

242PHP Programming with MySQL

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

Chapter 5

Working with Filesand Directories

PHP Programming with MySQL

244PHP Programming with MySQL

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

245PHP Programming with MySQL

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

246PHP Programming with MySQL

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

247PHP Programming with MySQL

Understanding File Types(continued)

248PHP Programming with MySQL

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.

249PHP Programming with MySQL

Understanding File Types(continued)

• Scripts written in a UNIX/Linux text editor display differently when opened in a Windows-based text editor

Figure 5-1 Volunteer registration form

250PHP Programming with MySQL

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)

251PHP Programming with MySQL

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

252PHP Programming with MySQL

Working with File Permissions(continued)

253PHP Programming with MySQL

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

254PHP Programming with MySQL

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

255PHP Programming with MySQL

Reading Directories

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

256PHP Programming with MySQL

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

257PHP Programming with MySQL

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);

258PHP Programming with MySQL

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

259PHP Programming with MySQL

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 />";

} …

260PHP Programming with MySQL

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";

}

261PHP Programming with MySQL

Reading Directories(continued)

Figure 5-3 Listing of the “files” subdirectory

using the scandir() function

262PHP Programming with MySQL

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");

263PHP Programming with MySQL

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");

264PHP Programming with MySQL

Creating Directories (continued)

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

265PHP Programming with MySQL

Obtaining File and Directory Information

266PHP Programming with MySQL

Obtaining File and Directory Information (continued)

267PHP Programming with MySQL

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 notexist.</p>";

268PHP Programming with MySQL

Obtaining File and Directory Information (continued)

Figure 5-5 Output of script with file and directory information functions

269PHP Programming with MySQL

Obtaining File and Directory Information (continued)

• The following table returns additional information about files and directories:

270PHP Programming with MySQL

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

271PHP Programming with MySQL

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

272PHP Programming with MySQL

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

273PHP Programming with MySQL

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

274PHP Programming with MySQL

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']

275PHP Programming with MySQL

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

276PHP Programming with MySQL

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.

277PHP Programming with MySQL

Storing the Uploaded File(continued)

• The function returns TRUE if the move succeeds, and FALSE if the move failsif (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";

elseecho "Successfully uploaded \"uploads/" . htmlentities($_FILES['picture_file']['name']) . "\"<br />\n";

278PHP Programming with MySQL

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

279PHP Programming with MySQL

Downloading Files(continued)

280PHP Programming with MySQL

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

281PHP Programming with MySQL

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])

282PHP Programming with MySQL

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);

283PHP Programming with MySQL

Writing an Entire File(continued)

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>";

• 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

284PHP Programming with MySQL

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

285PHP Programming with MySQL

Reading an Entire File

286PHP Programming with MySQL

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;

287PHP Programming with MySQL

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");

288PHP Programming with MySQL

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);

289PHP Programming with MySQL

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>";

}

290PHP Programming with MySQL

Reading an Entire File(continued)

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

291PHP Programming with MySQL

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 resource1. 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

292PHP Programming with MySQL

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

293PHP Programming with MySQL

Opening a File Stream (continued)

294PHP Programming with MySQL

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+”

295PHP Programming with MySQL

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+”

296PHP Programming with MySQL

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 doesn’t keep taking up space in your computer’s memory and allow other processes to read to and write from the file

297PHP Programming with MySQL

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

298PHP Programming with MySQL

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)

299PHP Programming with MySQL

Reading Data Incrementally

• The fgets() function uses the file pointer to iterate through a text file

300PHP Programming with MySQL

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

301PHP Programming with MySQL

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

302PHP Programming with MySQL

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

303PHP Programming with MySQL

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> ";

elseecho " <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> ");

304PHP Programming with MySQL

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)

305PHP Programming with MySQL

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

306PHP Programming with MySQL

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

307PHP Programming with MySQL

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

308PHP Programming with MySQL

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

309PHP Programming with MySQL

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

310PHP Programming with MySQL

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

311PHP Programming with MySQL

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

312PHP Programming with MySQL

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

313PHP Programming with MySQL

Summary (continued)

• An uploaded file’s 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

314PHP Programming with MySQL

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

315PHP Programming with MySQL

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");

316PHP Programming with MySQL

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

317PHP Programming with MySQL

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

318PHP Programming with MySQL

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

Chapter 6

Manipulating Arrays

PHP Programming with MySQL

320PHP Programming with MySQL

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

321PHP Programming with MySQL

Manipulating Elementsif (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";

}

}

322PHP Programming with MySQL

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>

 

323PHP Programming with MySQL

Manipulating Elements (continued)

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

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);

324PHP Programming with MySQL

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";

325PHP Programming with MySQL

326PHP Programming with MySQL

Manipulating Elements (continued)

Figure 6-2 Message Board page of the Message Board

327PHP Programming with MySQL

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 comma-

separated values for each element you want to add

328PHP Programming with MySQL

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";

329PHP Programming with MySQL

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

330PHP Programming with MySQL

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

331PHP Programming with MySQL

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");

332PHP Programming with MySQL

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);

333PHP Programming with MySQL

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");

334PHP Programming with MySQL

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", // first element (0)

"Molecular Biology", // second element (1)

"Neurology", // third element (2)

"Pediatrics"); // fourth element (3)

array_splice($HospitalDepts, 3, 0, array("Opthalmology",

"Otolaryngology"));

335PHP Programming with MySQL

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);

336PHP Programming with MySQL

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]);

337PHP Programming with MySQL

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

338PHP Programming with MySQL

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>";

 

339PHP Programming with MySQL

Removing Duplicate Elements (continued)

Figure 6-4 Output of an array after removing duplicate values with the array_unique() function

340PHP Programming with MySQL

Declaring and Initializing Associative Arrays

• With associative arrays, you specify an element’s 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

341PHP Programming with MySQL

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

342PHP Programming with MySQL

Iterating Through an Array

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

343PHP Programming with MySQL

Iterating Through an Array (continued)

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

344PHP Programming with MySQL

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

345PHP Programming with MySQL

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>";

346PHP Programming with MySQL

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

347PHP Programming with MySQL

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>";

}

348PHP Programming with MySQL

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);

349PHP Programming with MySQL

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";

}

350PHP Programming with MySQL

Returning a Portion of an Array (continued)

Figure 6-11 Output of an array returned with the array_slice() function

351PHP Programming with MySQL

Sorting Arrays

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

352PHP Programming with MySQL

Sorting Arrays (continued)

353PHP Programming with MySQL

Sorting Arrays (continued)

354PHP Programming with MySQL

Sorting Arrays (continued)

• If the sort() and rsort() functions are used on an associative array, the keys are replaced with indexes

355PHP Programming with MySQL

Sorting Arrays (continued)

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

356PHP Programming with MySQL

Sorting Arrays (continued)

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

357PHP Programming with MySQL

Sorting Arrays (continued)

Figure 6-14 Output of an associative array after sorting with the asort() function

358PHP Programming with MySQL

Sorting Arrays (continued)

Figure 6-15 Output of an associative array after sorting with the ksort() function

359PHP Programming with MySQL

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, ...);

360PHP Programming with MySQL

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";

361PHP Programming with MySQL

Combining Arrays (continued)

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

362PHP Programming with MySQL

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

363PHP Programming with MySQL

Comparing Arrays (continued)

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

364PHP Programming with MySQL

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";

365PHP Programming with MySQL

Comparing Arrays (continued)

Figure 6-20 Output of an array created with the array_intersect() function

366PHP Programming with MySQL

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);

367PHP Programming with MySQL

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

368PHP Programming with MySQL

Creating Two-Dimensional Indexed Arrays (continued)

$Gallons = array(

128, // ounces

16, // cups

8, // pints

4 // quarts

);

369PHP Programming with MySQL

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);

370PHP Programming with MySQL

Creating Two-Dimensional Indexed Arrays (continued)

$VolumeConversions = array($Ounces, $Cups, $Pints, $Quarts, $Gallons);

371PHP Programming with MySQL

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);

372PHP Programming with MySQL

Creating Two-Dimensional Associative Arrays (continued)

Figure 6-21 Elements and keys in the $VolumeConversions[ ] array

373PHP Programming with MySQL

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

);

374PHP Programming with MySQL

Working with Additional Dimensions

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

375PHP Programming with MySQL

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>

376PHP Programming with MySQL

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";

}

}

377PHP Programming with MySQL

Using Arrays in Web Forms(continued)

378PHP Programming with MySQL

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

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";

}

}

379PHP Programming with MySQL

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>

380PHP Programming with MySQL

381PHP Programming with MySQL

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

382PHP Programming with MySQL

Summary (continued)

• The unset() function removes array elements and other variables

• The array_values() function renumbers an indexed array’s 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

383PHP Programming with MySQL

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

384PHP Programming with MySQL

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

385PHP Programming with MySQL

Summary (continued)

• When using associative array notation in a Web form, you omit the quotation marks around the key name

Chapter 7

Working with Databasesand MySQL

PHP Programming with MySQL

387PHP Programming with MySQL

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

388PHP Programming with MySQL

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

389PHP Programming with MySQL

Introduction to Databases (continued)

Figure 7-1 Employee directory database

390PHP Programming with MySQL

Introduction to Databases (continued)

• A flat-file database stores information in a single table

• A relational database stores information across multiple related tables

391PHP Programming with MySQL

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

392PHP Programming with MySQL

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

393PHP Programming with MySQL

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

394PHP Programming with MySQL

One-to-One Relationships (continued)

Figure 7-2 One-to-one relationship

395PHP Programming with MySQL

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

396PHP Programming with MySQL

One-to-Many Relationship (continued)

Figure 7-3 Table with redundant information

397PHP Programming with MySQL

One-to-Many Relationship (continued)

Figure 7-4 One-to-many relationship

398PHP Programming with MySQL

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

399PHP Programming with MySQL

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

400PHP Programming with MySQL

Working with Database Management Systems

(continued)

Figure 7-5 Many-to-many relationship

401PHP Programming with MySQL

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 database’s tables, regardless of the database format

– Querying capability

402PHP Programming with MySQL

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

Getting Started withMySQL

403PHP Programming 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

404PHP Programming with MySQL

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 passwordmysql –u root

• Log out with the exit or quit commands

405PHP Programming with MySQL

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.9-nt

 

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

406PHP Programming with MySQL

Logging in to MySQL (continued)

Figure 7-6 MySQL Monitor on a Windows platform

408PHP Programming with MySQL

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

409PHP Programming with MySQL

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

410PHP Programming with MySQL

Getting Help with MySQL Commands

411PHP Programming with MySQL

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

412PHP Programming with MySQL

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 databasemysql> DROP DATABASE database;

413PHP Programming with MySQL

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

414PHP Programming with MySQL

Defining Database Tables(continued)

Creating Tables

• Use the CREATE TABLE statement to create a new table and define the column names and data types for each columnmysql> CREATE TABLE vehicles

(license VARCHAR(10), make VARCHAR(25),

model VARCHAR(50), miles FLOAT, assigned_to VARCHAR(40));[ENTER]

415PHP Programming with MySQL

Viewing Table Structure• Use the DESCRIBE table_name statement to view the structure of the table

416PHP Programming with MySQL

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]

417PHP Programming with MySQL

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]

418PHP Programming with MySQL

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]

419PHP Programming with MySQL

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]

420PHP Programming with MySQL

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]

421PHP Programming with MySQL

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.

422PHP Programming with MySQL

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

423PHP Programming with MySQL

Modifying User Privileges(continued)

424PHP Programming with MySQL

425PHP Programming with MySQL

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

426PHP Programming with MySQL

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

427PHP Programming with MySQL

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

428PHP Programming with MySQL

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]

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

429PHP Programming with MySQL

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]

430PHP Programming with MySQL

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]

431PHP Programming with MySQL

432PHP Programming with MySQL

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

433PHP Programming with MySQL

Retrieving Records (continued)

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

mysql> SELECT model, mileage FROM company_cars;[ENTER]

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

434PHP Programming with MySQL

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]

435PHP Programming with MySQL

436PHP Programming with MySQL

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]

437PHP Programming with MySQL

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]

438PHP Programming with MySQL

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]

439PHP Programming with MySQL

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]

440PHP Programming with MySQL

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]

441PHP Programming with MySQL

Updating Records

• To update records in a table, use the UPDATE statement

• The syntax for the UPDATE statement is:UPDATE table_nameSET column_name=valueWHERE 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

442PHP Programming with MySQL

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]

443PHP Programming with MySQL

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

444PHP Programming with MySQL

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

445PHP Programming with MySQL

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

446PHP Programming with MySQL

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

447PHP Programming with MySQL

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

448PHP Programming with MySQL

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

449PHP Programming with MySQL

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

450PHP Programming with MySQL

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

451PHP Programming with MySQL

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

452PHP Programming with MySQL

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

Chapter 8

Manipulating MySQLDatabases with PHP

PHP Programming with MySQL

454PHP Programming with MySQL

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

455PHP Programming with MySQL

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

456PHP Programming with MySQL

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

457PHP Programming with MySQL

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

458PHP Programming with MySQL

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

459PHP Programming with MySQL

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);

460PHP Programming with MySQL

Opening and Closing a MySQL Connection (continued)

461PHP Programming with MySQL

Opening and Closing a MySQL Connection (continued)

Figure 8-1 MySQLInfo.php in a Web browser

462PHP Programming with MySQL

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

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

463PHP Programming with MySQL

464PHP Programming with MySQL

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

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

465PHP Programming with MySQL

Creating a Database (continued)

Figure 8-2 Error message when the mysql_create_db() function is unavailable because of insufficient privileges

466PHP Programming with MySQL

467PHP Programming with MySQL

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

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

468PHP Programming with MySQL

469PHP Programming with MySQL

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

470PHP Programming with MySQL

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

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

471PHP Programming with MySQL

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>"; 472PHP Programming with MySQL

Creating and Deleting Tables (continued)

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

473PHP Programming with MySQL

474PHP Programming with MySQL

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);

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

475PHP Programming with MySQL

Creating and Deleting Tables (continued)

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

476PHP Programming with MySQL

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

477PHP Programming with MySQL

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

478PHP Programming with MySQL

479PHP Programming with MySQL

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);

480PHP Programming with MySQL

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

481PHP Programming with MySQL

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>";

482PHP Programming with MySQL

Using the mysql_affected_rows() Function (continued)

Figure 8-5 Output of mysql_affected_rows() function for an UPDATE query

483PHP Programming with MySQL

Using the mysql_info() Function

• For queries that add or update records, or alter a table’s 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

484PHP Programming with MySQL

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

485PHP Programming with MySQL

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>";

}

486PHP Programming with MySQL

Using the mysql_info() Function (continued)

Figure 8-6 Output of mysql_info() function for an INSERT query that adds multiple records

487PHP Programming with MySQL

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>";

}

488PHP Programming with MySQL

Using the mysql_info() Function (continued)

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

Working with Query Results

489PHP Programming with MySQL

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

490PHP Programming with MySQL

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";

491PHP Programming with MySQL

Retrieving Records into an Indexed Array

492PHP Programming with MySQL

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

493PHP Programming with MySQL

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

494PHP Programming with MySQL

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

495PHP Programming with MySQL

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

496PHP Programming with MySQL

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);

497PHP Programming with MySQL

Accessing Query Result Information (continued)

Figure 8-10 Output of the number of rows and fields returned from a query

498PHP Programming with MySQL

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

499PHP Programming with MySQL

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

500PHP Programming with MySQL

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

501PHP Programming with MySQL

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

502PHP Programming with MySQL

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

503PHP Programming with MySQL

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.

504PHP Programming with MySQL

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

505PHP Programming with MySQL

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

Chapter 9

Managing State Information

PHP Programming with MySQL

507PHP Programming with MySQL

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

508PHP Programming with MySQL

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

509PHP Programming with MySQL

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

510PHP Programming with MySQL

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

511PHP Programming with MySQL

Understanding State Information (continued)

Figure 9-1 College Internship Available OpportunitiesWeb site page flow

512PHP Programming with MySQL

Understanding State Information (continued)

Figure 9-2 Registration/Log In Web page

513PHP Programming with MySQL

Understanding State Information (continued)

Figure 9-3 New Intern Registration Web pageafter successful registration

514PHP Programming with MySQL

Understanding State Information (continued)

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

515PHP Programming with MySQL

Understanding State Information (continued)

Figure 9-5 The Available Opportunities Web pagewith the Intern information at top of screen

516PHP Programming with MySQL

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">

517PHP Programming with MySQL

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

518PHP Programming with MySQL

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";

519PHP Programming with MySQL

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

520PHP Programming with MySQL

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 server-side 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>

521PHP Programming with MySQL

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

522PHP Programming with MySQL

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 user’s computer

523PHP Programming with MySQL

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 user’s computer

• Total cookies per browser cannot exceed 300 • The largest cookie size is 4 kilobytes

524PHP Programming with MySQL

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

525PHP Programming with MySQL

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

526PHP Programming with MySQL

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

527PHP Programming with MySQL

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>

...

528PHP Programming with MySQL

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");

529PHP Programming with MySQL

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");

530PHP Programming with MySQL

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");

531PHP Programming with MySQL

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 cookie’s expiration time, use PHP’s time() function

setcookie("firstName", "Don", time()+3600);

532PHP Programming with MySQL

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 pathsetcookie("firstName", "Don", time()+3600, "/marketing/");

533PHP Programming with MySQL

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 domainsetcookie("firstName", "Don”, time()+3600, "/", ".gosselin.com");

534PHP Programming with MySQL

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);

535PHP Programming with MySQL

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

536PHP Programming with MySQL

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']}.";

537PHP Programming with MySQL

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]}.";

538PHP Programming with MySQL

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);

539PHP Programming with MySQL

Using Sessions to Save State Information

• Spyware gathers user information from a local computer for marketing and advertising purposes without the user’s 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

540PHP Programming with MySQL

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_

541PHP Programming with MySQL

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();

...

542PHP Programming with MySQL

Starting a Session (continued)

• You must call the session_start() function before you send the Web browser any output

• If a client’s 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

543PHP Programming with MySQL

Starting a Session (continued)

<?php

session_start();

...

?>

<p><a href='<?php echo "Occupation.php?PHPSESSID="

. session_id() ?>'>Occupation</a></p>

544PHP Programming with MySQL

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

545PHP Programming with MySQL

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>

546PHP Programming with MySQL

Working with Session Variables (continued)

• Use the isset() function to ensure that a session variable is set before you attempt to use it

<?phpsession_start();if (isset($_SESSION['firstName']) &&

isset($_SESSION['lastName'])&& isset($_SESSION['occupation']))

echo "<p>" . $_SESSION['firstName'] . " ". $_SESSION['lastName'] . " is a ". $_SESSION['occupation'] . "</p>";

?>

547PHP Programming with MySQL

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

548PHP Programming with MySQL

Deleting a Session (continued)

<?php

session_start();

$_SESSION = array();

session_destroy();

?>

549PHP Programming with MySQL

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

550PHP Programming with MySQL

Summary (continued)

• One way to preserve information following a user’s 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.

551PHP Programming with MySQL

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 user’s 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

552PHP Programming with MySQL

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

553PHP Programming with MySQL

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

554PHP Programming with MySQL

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.

555PHP Programming with MySQL

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 client’s Web browser is configured to accept cookies, the session ID is assigned to a temporary cookie named PHPSESSID.

556PHP Programming with MySQL

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

557PHP Programming with MySQL

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

Chapter 10

Developing Object-Oriented PHP

PHP Programming with MySQL

559PHP Programming with MySQL

Objectives

In this chapter, you will:• Study object-oriented programming concepts• Use objects in PHP scripts• Declare data members in classes• Work with class member functions

560PHP Programming with MySQL

Introduction to Object-Oriented Programming

• Object-oriented programming (OOP) refers the concept of merging related variables and functions into a single interface

• An object refers to programming code and data that can be treated as an individual unit or component

• Objects are often also called components

561PHP Programming with MySQL

Introduction to Object-Oriented Programming (continued)

• Data refers to information contained within variables or other types of storage structures

• The functions associated with an object are called methods

• The variables that are associated with an object are called properties or attributes

• Popular object-oriented programming languages include C++, Java, and Visual Basic

562PHP Programming with MySQL

Introduction to Object-Oriented Programming (continued)

Figure 10-1 Accounting program

563PHP Programming with MySQL

Understanding Encapsulation

• Objects are encapsulated – all code and required data are contained within the object itself

• Encapsulated objects hide all internal code and data

• An interface refers to the methods and properties that are required for a source program to communicate with an object

564PHP Programming with MySQL

Understanding Encapsulation (continued)

• Encapsulated objects allow users to see only the methods and properties of the object that you allow them to see

• Encapsulation reduces the complexity of the code

• Encapsulation prevents other programmers from accidentally introducing a bug into a program, or stealing code

565PHP Programming with MySQL

Object-Oriented Programming and Classes

• The code, methods, attributes, and other information that make up an object are organized into classes

• An instance is an object that has been created from an existing class

• Creating an object from an existing class is called instantiating the object

• An object inherits its methods and properties from a class — it takes on the characteristics of the class on which it is based

566PHP Programming with MySQL

Using Objects in PHP Scripts

• Declare an object in PHP by using the new operator with a class constructor

• A class constructor is a special function with the same name as its class that is called automatically when an object from the class is instantiated

• The syntax for instantiating an object is:$ObjectName = new ClassName();

567PHP Programming with MySQL

Using Objects in PHP Scripts (continued)

• After an object is instantiated, use a hyphen and a greater-than symbol (->) to access the methods and properties contained in the object

• Together, these two characters are referred to as member selection notation

• With member selection notation, one or more characters are appended to an object, followed by the name of a method or property

568PHP Programming with MySQL

Using Objects in PHP Scripts (continued)

• With methods, include a set of parentheses at the end of the method name, just as with functions

• Like functions, methods can also accept arguments

$Checking->getBalance();

$CheckNumber = 1022;

$Checking->getCheckAmount($CheckNumber);

569PHP Programming with MySQL

Working with Database Connections as Objects

• Access MySQL database connections as objects by instantiating an object from the mysqli class

• To connect to a MySQL database server using procedural syntax:

$DBConnect = mysql_connect("php_db", "dongosselin", "rosebud");

mysql_select_db("real_estate", $DBConnect);

• To connect to the MySQL database server using object-oriented style:

$DBConnect = new mysqli("php_db", "dongosselin","rosebud", "real_estate");

570PHP Programming with MySQL

Handling MySQL Errors

• This statement uses the mysqli() constructor function to instantiate a mysqli class object named $DBConnect

$DBConnect = @new mysqli("php_db", "dgosselin",

"rosebud");

• To explicitly close the database connection, use the close() method of the mysqli class $DBConnect->close();

571PHP Programming with MySQL

Handling MySQL Errors (continued)

• With object-oriented style, check whether a value is assigned to the mysqli_connect_errno() or mysqli_connect_error() functions

$DBConnect = @new mysqli("php.db", "dgosselin", "rosebud");

if ($DBConnect->connect_errno){ echo("<p>Unable to connect to the database

server.</p>" . "<p>Error code " . $DBConnect->connect_errno . ": " . $DBConnect->connect_error. "</p>\n";else {//code to execute if the connection fails}

572PHP Programming with MySQL

Executing SQL Statements

• With object-oriented style, use the query() method of the mysqli class

• To return the fields in the current row of a resultset into an indexed array use:– The fetch_row() method of the mysqli

class

• To return the fields in the current row of a resultset into an associative array use:– The fetch_assoc() method of the msqli

class

573PHP Programming with MySQL

Executing SQL Statements (continued)

$TableName = "company_cars";

$SQLstring = "SELECT * FROM $TableName";

$QueryResult = @$DBConnect->query($SQLstring);

if ($QueryResult === FALSE)

echo "<p>Unable to execute the query. " .

"Error code " . $DBConnect->errno .

": " . $DBConnect->error . "</p>\n";

else {

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";

574PHP Programming with MySQL

Executing SQL Statements (continued)

while (($Row = $QueryResult->fetch_row()) !== 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";

}

575PHP Programming with MySQL

Defining Custom PHP Classes

• Data structure refers to a system for organizing data

• The functions and variables defined in a class are called class members

• Class variables are referred to as data members or member variables

• Class functions are referred to as member functions or function members

576PHP Programming with MySQL

Defining Custom PHP Classes (continued)

• Classes: – Help make complex programs easier to manage– Hide information that users of a class do not need

to access or know about– Make it easier to reuse code or distribute your

code to others for use in their programs• Inherited characteristics allow you to build new

classes based on existing classes without having to rewrite the code contained in the existing one

577PHP Programming with MySQL

Creating a Class Definition

• To create a class in PHP, use the class keyword to write a class definition

• A class definition contains the data members and member functions that make up the class

• The syntax for defining a class is:

class ClassName {

data member and member function definitions

}

578PHP Programming with MySQL

Creating a Class Definition (continued)

• The ClassName portion of the class definition is the name of the new class

• Class names usually begin with an uppercase letter to distinguish them from other identifiers

• Within the class’s curly braces, declare the data type and field names for each piece of information stored in the structure

class BankAccount { data member and member function definitions } $Checking = new BankAccount();

579PHP Programming with MySQL

Creating a Class Definition (continued)

• Class names in a class definition are not followed by parentheses, as are function names in a function definition

$Checking = new BankAccount();echo 'The $Checking object is instantiated from the '

. get_class($Checking) . " class.</p>";

• Use the instanceof operator to determine whether an object is instantiated from a given class

• Use the class_exists() to determine if a class exists

580PHP Programming with MySQL

Storing Classes in External Files

• PHP provides the following functions that allow you to use external files in your PHP scripts: – include() – require()– include_once()– require_once()

• You pass to each function the name and path of the external file you want to use

581PHP Programming with MySQL

Storing Classes in External Files (continued)

• include() and require() functions both insert the contents of an external file, called an include file, into a PHP script

• include_once() and require_once() functions only include an external file once during the processing of a script

• Any PHP code must be contained within a PHP script section (<?php ... ?>) in an external file

582PHP Programming with MySQL

Collecting Garbage

• Garbage collection refers to cleaning up or reclaiming memory that is reserved by a program

• PHP knows when your program no longer needs a variable or object and automatically cleans up the memory for you

• The one exception is with open database connections

583PHP Programming with MySQL

Information Hiding

• Information hiding states that any class members that other programmers, sometimes called clients, do not need to access or know about should be hidden

• Helps minimize the amount of information that needs to pass in and out of an object

• Reduces the complexity of the code that clients see

• Prevents other programmers from accidentally introducing a bug into a program by modifying a class’s internal workings

584PHP Programming with MySQL

Using Access Specifiers

• Access specifiers control a client’s access to individual data members and member functions

• There are three levels of access specifiers in PHP: public, private, and protected

• The public access specifier allows anyone to call a class’s member function or to modify and retrieve a data member

585PHP Programming with MySQL

Using Access Specifiers (continued)

• The private access specifier prevents clients from calling member functions or accessing data members and is one of the key elements in information hiding

• Private access does not restrict a class’s internal access to its own members

• Private access restricts clients from accessing class members

586PHP Programming with MySQL

Using Access Specifiers (continued)

• Include an access specifier at the beginning of a data member declaration statement

class BankAccount { public $Balance = 0;}

• Always assign an initial value to a data member when you first declare it

class BankAccount { public $Balance = 1 + 2;}

587PHP Programming with MySQL

Serializing Objects

• Serialization refers to the process of converting an object into a string that you can store for reuse

• Serialization stores both data members and member functions into strings

• To serialize an object, pass an object name to the serialize() function

$SavedAccount = serialize($Checking);

588PHP Programming with MySQL

Serializing Objects (continued)

• To convert serialized data back into an object, you use the unserialize() function

$Checking = unserialize($SavedAccount);

• Serialization is also used to store the data in large arrays

• To use serialized objects between scripts, assign a serialized object to a session variable

session_start();

$_SESSION('SavedAccount') = serialize($Checking);

589PHP Programming with MySQL

Working with Member Functions

• Create public member functions for any functions that clients need to access

• Create private member functions for any functions that clients do not need to access

• Access specifiers control a client’s access to individual data members and member functions

590PHP Programming with MySQL

Working with Member Functions (continued)

class BankAccount {public $Balance = 958.20;public function withdrawal($Amount) {

$this->Balance -= $Amount;}

}if (class_exists("BankAccount"))

$Checking = new BankAccount();else

exit("<p>The BankAccount class is not available!</p>");printf("<p>Your checking account balance is $%.2f.</p>",

$Checking->Balance);$Cash = 200;$Checking->withdrawal(200);printf("<p>After withdrawing $%.2f, your checking account

balance is $%.2f.</p>", $Cash, $Checking->Balance);

591PHP Programming with MySQL

Using the $this Reference

• Outside of a class, refer to the members of the object using the name of the object, the member selection nation (-), and the name of the function or variable

• Within a class function definition, use $this to refer to the current object of the class

$this->AccountNumber = 0;

592PHP Programming with MySQL

Initializing with Constructor Functions

• A constructor function is a special function that is called automatically when an object from a class is instantiatedclass BankAccount {

private $AccountNumber;private $CustomerName;private $Balance;function __construct() {

$this->AccountNumber = 0;$this->Balance = 0;$this->CustomerName = "";

}}

593PHP Programming with MySQL

Initializing with Constructor Functions (continued)

• The __construct() function takes precedence over a function with the same name as the class

• Constructor functions are commonly used in PHP to handle database connection tasks

594PHP Programming with MySQL

Cleaning Up with Destructor Functions

• A default constructor function is called when a class object is first instantiated

• A destructor function is called when the object is destroyed

• A destructor function cleans up any resources allocated to an object after the object is destroyed

595PHP Programming with MySQL

Cleaning Up with Destructor Functions (continued)

• A destructor function is commonly called in two ways: – When a script ends

– When you manually delete an object with the unset() function

• To add a destructor function to a PHP class, create a function named __destruct()

596PHP Programming with MySQL

Cleaning Up with Destructor Functions (continued)

function __construct() {

$DBConnect = new mysqli("php_db", "dongosselin","rosebud", "real_estate");

}

function __destruct() {

$DBConnect->close();

}

597PHP Programming with MySQL

Writing Accessor Functions

• Accessor functions are public member functions that a client can call to retrieve or modify the value of a data member

• Accessor functions often begin with the words “set” or “get”

• Set functions modify data member values• Get functions retrieve data member values

598PHP Programming with MySQL

Writing Accessor Functions (continued)

class BankAccount {private $Balance = 0;public function setBalance($NewValue) {

$this->Balance = $NewValue;}public function getBalance() {

return $this->Balance;}

}if (class_exists("BankAccount"))

$Checking = new BankAccount();else

exit("<p>The BankAccount class is not available!</p>");$Checking->setBalance(100);echo "<p>Your checking account balance is "

. $Checking->getBalance() . "</p>\n";

599PHP Programming with MySQL

Serialization Functions

• When you serialize an object with the serialize() function, PHP looks in the object’s class for a special function named __sleep()

• The primary reason for including a __sleep() function in a class is to specify which data members of the class to serialize

600PHP Programming with MySQL

Serialization Functions (continued)

• If you do not include a __sleep() function in your class, the serialize() function serializes all of its data members

function __sleep() {$SerialVars = array('Balance');return $SerialVars;

}

• When the unserialize() function executes, PHP looks in the object’s class for a special function named __wakeup()

601PHP Programming with MySQL

Summary

• The term “object-oriented programming (OOP)” refers to the creation of reusable software objects that can be easily incorporated into multiple programs. The term “object” specifically refers to programming code and data that can be treated as an individual unit or component (object)

• The term “data” refers to information contained within variables or other types of storage structures

602PHP Programming with MySQL

Summary (continued)

• The functions associated with an object are called methods, and the variables associated with an object are called properties or attributes

• Objects are encapsulated, which means that all code and required data are contained within the object itself

• An interface represents elements required for a source program to communicate with an object

603PHP Programming with MySQL

Summary (continued)

• In object-oriented programming, the code, methods, attributes, and other information that make up an object are organized into classes

• An instance is an object that has been created from an existing class. When you create an object from an existing class, you are “instantiating the object”

604PHP Programming with MySQL

Summary (continued)

• A particular instance of an object inherits its methods and properties from a class—that is, it takes on the characteristics of the class on which it is based

• A constructor is a special function with the same name as its class; it is called automatically when an object from the class is instantiated

• The term “data structure” refers to a system for organizing data

605PHP Programming with MySQL

Summary (continued)

• The functions and variables defined in a class are called class members. Class variables are referred to as data members or member variables, whereas class functions are referred to as member functions or function members

• A class definition contains the data members and member functions that make up the class

606PHP Programming with MySQL

Summary (continued)

• PHP provides the following functions that allow you to use external files in your PHP scripts: include(), require(), include_once(), and require_once()

• The principle of information hiding states that class members should be hidden when other programmers do not need to access or know about them

• Access specifiers control a client’s access to individual data members and member functions

607PHP Programming with MySQL

Summary (continued)

• Serialization refers to the process of converting an object into a string that you can store for reuse

• A constructor function is a special function that is called automatically when an object from a class is instantiated

• A destructor function cleans up any resources allocated to an object after the object is destroyed

608PHP Programming with MySQL

Summary (continued)

• Accessor functions are public member functions that a client can call to retrieve the value of a data member

• Mutator functions are public member functions that a client can call to modify the value of a data member

609PHP Programming with MySQL

Summary (continued)

• When you serialize an object with the serialize() function, PHP looks in the object’s class for a special function named __sleep(), which you can use to perform many of the same tasks as a destructor function

• When the unserialize() function executes, PHP looks in the object’s class for a special function named __wakeup(), which you can use to perform many of the same tasks as a constructor function