php_mysql training

556
Chapter 1 Getting Started with PHP 2 nd Edition

Upload: dsunte-wilson

Post on 15-Jul-2016

8 views

Category:

Documents


4 download

DESCRIPTION

Php and Mysql Training

TRANSCRIPT

Page 1: php_mysql Training

Chapter 1

Getting Started with PHP

2nd Edition

Page 2: php_mysql Training

2

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

Page 3: php_mysql Training

3

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

Page 4: php_mysql Training

4

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

Page 5: php_mysql Training

5

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

Page 6: php_mysql Training

6

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

Page 7: php_mysql Training

7

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

Page 8: php_mysql Training

8

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

Page 9: php_mysql Training

9

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

Page 10: php_mysql Training

10

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

Page 11: php_mysql Training

Displaying Script Results

• The echo and print statements are language constructs (built-in features of a programming language) that create new text on a Web page that is returned as a response to a client

• The text passed to the echo statement is called a “literal string” and must be enclosed in either single or double quotation marks

• To pass multiple arguments to the echo statement, separate the statements with commas

11

Page 12: php_mysql Training

12

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

Page 13: php_mysql Training

13

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>

Page 14: php_mysql Training

14

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>

Page 15: php_mysql Training

15

Creating Multiple Code Declaration Blocks (continued)

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

Page 16: php_mysql Training

16

Creating Multiple Code Declaration Blocks (continued)

Figure 1-10 PHP Environment Information Web page

Page 17: php_mysql Training

17

Case Sensitivity in PHP

• Programming language constructs in PHP are mostly case insensitive

<?phpecho "<p>Explore <strong>Africa</strong>, <br />";Echo "<strong>South America</strong>, <br />";ECHO " and <strong>Australia</strong>!</p>";?>

Page 18: php_mysql Training

18

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

Page 19: php_mysql Training

19

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

Page 20: php_mysql Training

20

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

Page 21: php_mysql Training

21

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

Page 22: php_mysql Training

22

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

Page 23: php_mysql Training

23

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

Page 24: php_mysql Training

24

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;

Page 25: php_mysql Training

25

Displaying Variables

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

Page 26: php_mysql Training

26

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

Page 27: php_mysql Training

27

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

Page 28: php_mysql Training

28

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

Page 29: php_mysql Training

29

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

Page 30: php_mysql Training

30

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

Page 31: php_mysql Training

31

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

Page 32: php_mysql Training

32

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)

Page 33: php_mysql Training

33

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

Page 34: php_mysql Training

34

Arrays

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

Figure 1-17 Conceptual example of an array

Page 35: php_mysql Training

35

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]

Page 36: php_mysql Training

36

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

Page 37: php_mysql Training

37

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

Page 38: php_mysql Training

38

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

Page 39: php_mysql Training

39

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

Page 40: php_mysql Training

40

Accessing Element Information (continued)

Figure 1-19 Output of the count() function

Page 41: php_mysql Training

41

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

Page 42: php_mysql Training

42

Accessing Element Information (continued)

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

Page 43: php_mysql Training

43

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

Page 44: php_mysql Training

44

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

Page 45: php_mysql Training

45

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

Page 46: php_mysql Training

46

Building Expressions (continued)

Page 47: php_mysql Training

47

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

Page 48: php_mysql Training

48

Arithmetic Operators

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

Page 49: php_mysql Training

49

Arithmetic Operators (continued)

Figure 1-22 Results of arithmetic expressions

Page 50: php_mysql Training

50

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

Page 51: php_mysql Training

51

Arithmetic Binary Operators

Page 52: php_mysql Training

52

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

Page 53: php_mysql Training

53

Arithmetic Unary Operators (continued)

Figure 1-24 Script that uses the prefix increment operator

Page 54: php_mysql Training

54

Arithmetic Unary Operators (continued)

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

Page 55: php_mysql Training

55

Arithmetic Unary Operators (continued)

Figure 1-26 Script that uses the postfix increment operator

Page 56: php_mysql Training

56

Arithmetic Unary Operators (continued)

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

Page 57: php_mysql Training

57

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

Page 58: php_mysql Training

58

Assignment Operators (continued)

Page 59: php_mysql Training

59

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

Page 60: php_mysql Training

60

Comparison and Conditional Operators (continued)

Page 61: php_mysql Training

61

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

Page 62: php_mysql Training

62

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

Page 63: php_mysql Training

63

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

Page 64: php_mysql Training

64

Special Operators

Page 65: php_mysql Training

65

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

Page 66: php_mysql Training

66

Type Casting (continued)

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

Page 67: php_mysql Training

67

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

Page 68: php_mysql Training

68

Understanding Operator Precedence (continued)

Page 69: php_mysql Training

69

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

Page 70: php_mysql Training

70

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

Page 71: php_mysql Training

71

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

Page 72: php_mysql Training

72

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

Page 73: php_mysql Training

73

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.

Page 74: php_mysql Training

74

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

Page 75: php_mysql Training

75

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

Page 76: php_mysql Training

76

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

Page 77: php_mysql Training

Chapter 2

Functions and ControlStructures

2nd Edition

Page 78: php_mysql Training

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

Page 79: php_mysql Training

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:<?phpfunction name_of_function(parameters) { statements;}?>

79

Page 80: php_mysql Training

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

Page 81: php_mysql Training

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

Page 82: php_mysql Training

Calling Functionsfunction displayCompanyName($CompanyName) {

echo "<p>$CompanyName</p>";}displayCompanyName("Course Technology");

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

82

Page 83: php_mysql Training

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

Page 84: php_mysql Training

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

Page 85: php_mysql Training

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

Page 86: php_mysql Training

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

Page 87: php_mysql Training

The global Keyword (continued)

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

87

Page 88: php_mysql Training

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

Page 89: php_mysql Training

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

Page 90: php_mysql Training

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

Page 91: php_mysql Training

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

Page 92: php_mysql Training

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

Page 93: php_mysql Training

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

Page 94: php_mysql Training

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

Page 95: php_mysql Training

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

Page 96: php_mysql Training

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

Page 97: php_mysql Training

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

Page 98: php_mysql Training

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

Page 99: php_mysql Training

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

Page 100: php_mysql Training

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

Page 101: php_mysql Training

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

Page 102: php_mysql Training

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

Page 103: php_mysql Training

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

Page 104: php_mysql Training

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

Page 105: php_mysql Training

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

Page 106: php_mysql Training

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

Page 107: php_mysql Training

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

Page 108: php_mysql Training

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

Page 109: php_mysql Training

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

Page 110: php_mysql Training

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

Page 111: php_mysql Training

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

Page 112: php_mysql Training

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

Page 113: php_mysql Training

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

Page 114: php_mysql Training

foreach Statements (continued)

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

foreach ($DaysOfWeek as $Day) { echo "<p>$Day</p>";}

114

Page 115: php_mysql Training

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

Page 116: php_mysql Training

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

Page 117: php_mysql Training

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

Page 118: php_mysql Training

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

Page 119: php_mysql Training

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

Page 120: php_mysql Training

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

Page 121: php_mysql Training

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

Page 122: php_mysql Training

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

Page 123: php_mysql Training

Chapter 3

Manipulating Strings

2nd Edition

Page 124: php_mysql Training

124

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

Page 125: php_mysql Training

125

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)

Page 126: php_mysql Training

126

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

Page 127: php_mysql Training

127

Constructing Text Strings (continued)

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

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

Page 128: php_mysql Training

128

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;

Page 129: php_mysql Training

129

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;

Page 130: php_mysql Training

130

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

Page 131: php_mysql Training

131

Adding Escape Characters and Sequences (continued)

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

Page 132: php_mysql Training

132

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

Page 133: php_mysql Training

133

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

Page 134: php_mysql Training

134

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

Page 135: php_mysql Training

135

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

Page 136: php_mysql Training

136

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

Page 137: php_mysql Training

137

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

Page 138: php_mysql Training

138

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

Page 139: php_mysql Training

139

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

Page 140: php_mysql Training

140

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

Page 141: php_mysql Training

141

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

Page 142: php_mysql Training

142

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

Page 143: php_mysql Training

143

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

Page 144: php_mysql Training

144

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

Page 145: php_mysql Training

145

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

Page 146: php_mysql Training

146

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

Page 147: php_mysql Training

147

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

Page 148: php_mysql Training

148

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

Page 149: php_mysql Training

149

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

Page 150: php_mysql Training

150

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

Page 151: php_mysql Training

151

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

Page 152: php_mysql Training

152

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

Page 153: php_mysql Training

153

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

Page 154: php_mysql Training

154

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

Page 155: php_mysql Training

155

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

Page 156: php_mysql Training

156

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

Page 157: php_mysql Training

157

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

Page 158: php_mysql Training

158

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

Page 159: php_mysql Training

159

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

Page 160: php_mysql Training

160

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

Page 161: php_mysql Training

161

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

elseecho "<p>The second letter is lower in the alphabet than

The first letter.</p>";

Page 162: php_mysql Training

162

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

Page 163: php_mysql Training

163

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

Page 164: php_mysql Training

164

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

Page 165: php_mysql Training

165

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

Page 166: php_mysql Training

166

Determining the Similarity of Two Strings (continued)

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

Page 167: php_mysql Training

167

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

Page 168: php_mysql Training

168

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

elseecho "<p>The names are not pronounced the

same.</p>";

Page 169: php_mysql Training

169

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

Page 170: php_mysql Training

170

Working with Regular Expressions(continued)

Page 171: php_mysql Training

171

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

Page 172: php_mysql Training

172

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

Page 173: php_mysql Training

173

Writing Regular Expression Patterns

(continued)

Page 174: php_mysql Training

174

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

Page 175: php_mysql Training

175

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

Page 176: php_mysql Training

176

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

Page 177: php_mysql Training

177

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

Page 178: php_mysql Training

178

Specifying Quantity

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

Page 179: php_mysql Training

179

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

Page 180: php_mysql Training

180

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

Page 181: php_mysql Training

181

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

Page 182: php_mysql Training

182

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

Page 183: php_mysql Training

183

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

Page 184: php_mysql Training

184

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 1preg_match("/analy[sz]e/", "analyze");//returns 1

preg_match("/analy[sz]e/", "analyce");//returns 0

Page 185: php_mysql Training

185

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

Page 186: php_mysql Training

186

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

Page 187: php_mysql Training

187

Defining Character Classes(continued)

Page 188: php_mysql Training

188

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

Page 189: php_mysql Training

189

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

Page 190: php_mysql Training

190

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

Page 191: php_mysql Training

191

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

Page 192: php_mysql Training

192

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

Page 193: php_mysql Training

193

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

Page 194: php_mysql Training

194

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

Page 195: php_mysql Training

195

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

Page 196: php_mysql Training

196

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

Page 197: php_mysql Training

197

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

Page 198: php_mysql Training

198

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

Page 199: php_mysql Training

Chapter 4

Handling User Input

2nd Edition

Page 200: php_mysql Training

200

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

Page 201: php_mysql Training

201

Using Autoglobals

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

Page 202: php_mysql Training

202

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

Page 203: php_mysql Training

203

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

Page 204: php_mysql Training

204

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

Page 205: php_mysql Training

205

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

Page 206: php_mysql Training

206

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

Page 207: php_mysql Training

207

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

Page 208: php_mysql Training

208

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

Page 209: php_mysql Training

209

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

Page 210: php_mysql Training

210

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

Page 211: php_mysql Training

211

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

Page 212: php_mysql Training

212

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

Page 213: php_mysql Training

213

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

Page 214: php_mysql Training

Handling Special Characters(continued)

214

Page 215: php_mysql Training

Handling Special Characters(continued)

• The addslashes() function adds a backslash before a single or double quote or a NULL character in user input (if magic quotes is disabled, this is the alternative to escape a character before saving to a text file or database)

• The stripslashes() function removes a backslash before a single or double quote or NULL character in user input (if magic quotes is enabled, this is required before outputting a string with the echo statement)

215

Page 216: php_mysql Training

216

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

Page 217: php_mysql Training

217

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

Page 218: php_mysql Training

218

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

Page 219: php_mysql Training

219

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

Page 220: php_mysql Training

220

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

Page 221: php_mysql Training

221

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

Page 222: php_mysql Training

222

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>

Page 223: php_mysql Training

223

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

Page 224: php_mysql Training

224

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.

Page 225: php_mysql Training

225

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

Page 226: php_mysql Training

226

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

Page 227: php_mysql Training

227

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

Page 228: php_mysql Training

228

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}

Page 229: php_mysql Training

229

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

Page 230: php_mysql Training

230

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

Page 231: php_mysql Training

231

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>

Page 232: php_mysql Training

232

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”

Page 233: php_mysql Training

233

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

Page 234: php_mysql Training

234

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 pageinclude('inc_home.html');break;default:include('inc_home.html');break;

}}

Page 235: php_mysql Training

235

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

Page 236: php_mysql Training

236

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

Page 237: php_mysql Training

237

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

Page 238: php_mysql Training

238

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

Page 239: php_mysql Training

239

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

Page 240: php_mysql Training

240

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

Page 241: php_mysql Training

241

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)

Page 242: php_mysql Training

242

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

Page 243: php_mysql Training

Chapter 5

Working with Filesand Directories

2nd Edition

Page 244: php_mysql Training

244

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

Page 245: php_mysql Training

245

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

Page 246: php_mysql Training

246

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

Page 247: php_mysql Training

247

Understanding File Types(continued)

Page 248: php_mysql Training

248

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.

Page 249: php_mysql Training

249

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

Page 250: php_mysql Training

250

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)

Page 251: php_mysql Training

251

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

Page 252: php_mysql Training

252

Working with File Permissions(continued)

Page 253: php_mysql Training

253

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

Page 254: php_mysql Training

254

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

Page 255: php_mysql Training

255

Reading Directories

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

Page 256: php_mysql Training

256

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

Page 257: php_mysql Training

257

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

Page 258: php_mysql Training

258

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

Page 259: php_mysql Training

259

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

} …

Page 260: php_mysql Training

260

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

}

Page 261: php_mysql Training

261

Reading Directories(continued)

Figure 5-3 Listing of the “files” subdirectory using the scandir() function

Page 262: php_mysql Training

262

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

Page 263: php_mysql Training

263

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

Page 264: php_mysql Training

264

Creating Directories (continued)

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

Page 265: php_mysql Training

265

Obtaining File and Directory Information

Page 266: php_mysql Training

266

Obtaining File and Directory Information (continued)

Page 267: php_mysql Training

267

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

Page 268: php_mysql Training

268

Obtaining File and Directory Information (continued)

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

Page 269: php_mysql Training

269

Obtaining File and Directory Information (continued)

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

Page 270: php_mysql Training

270

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

Page 271: php_mysql Training

271

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

Page 272: php_mysql Training

272

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

Page 273: php_mysql Training

273

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

Page 274: php_mysql Training

274

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

Page 275: php_mysql Training

275

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

Page 276: php_mysql Training

276

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.

Page 277: php_mysql Training

277

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

Page 278: php_mysql Training

278

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

Page 279: php_mysql Training

279

Downloading Files(continued)

Page 280: php_mysql Training

280

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

Page 281: php_mysql Training

281

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

Page 282: php_mysql Training

282

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

Page 283: php_mysql Training

283

Writing an Entire File(continued)

if (file_put_contents($VolunteersFile, $EventVolunteers) > 0)echo "<p>Data was successfully written to the $VolunteersFile file.</p>";

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

Page 284: php_mysql Training

284

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

Page 285: php_mysql Training

285

Reading an Entire File

Page 286: php_mysql Training

286

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

Page 287: php_mysql Training

287

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

Page 288: php_mysql Training

288

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

Page 289: php_mysql Training

289

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

}

Page 290: php_mysql Training

290

Reading an Entire File(continued)

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

Page 291: php_mysql Training

291

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() function2. Write data to or read data from the file stream3. Close the file stream with the fclose() function

Page 292: php_mysql Training

292

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

Page 293: php_mysql Training

293

Opening a File Stream (continued)

Page 294: php_mysql Training

294

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

Page 295: php_mysql Training

295

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

Page 296: php_mysql Training

296

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

Page 297: php_mysql Training

297

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

Page 298: php_mysql Training

298

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)

Page 299: php_mysql Training

299

Reading Data Incrementally

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

Page 300: php_mysql Training

300

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

Page 301: php_mysql Training

301

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

Page 302: php_mysql Training

302

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

Page 303: php_mysql Training

303

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

Page 304: php_mysql Training

304

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)

Page 305: php_mysql Training

305

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

Page 306: php_mysql Training

306

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

Page 307: php_mysql Training

307

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

Page 308: php_mysql Training

308

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

Page 309: php_mysql Training

309

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

Page 310: php_mysql Training

310

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

Page 311: php_mysql Training

311

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

Page 312: php_mysql Training

312

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

Page 313: php_mysql Training

313

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

Page 314: php_mysql Training

314

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

Page 315: php_mysql Training

315

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

Page 316: php_mysql Training

316

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

Page 317: php_mysql Training

317

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

Page 318: php_mysql Training

318

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

Page 319: php_mysql Training

Chapter 6

Manipulating Arrays

2nd Edition

Page 320: php_mysql Training

320

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

Page 321: php_mysql Training

321

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

Page 322: php_mysql Training

322

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> 

Page 323: php_mysql Training

323

Manipulating Elements (continued)

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

Page 324: php_mysql Training

Manipulating Elements (continued)

<h1>Message Board</h1><?php?><p><a href="PostMessage.php">Post New Message</a></p>if ((!file_exists("MessageBoard/messages.txt")) ||

(filesize("MessageBoard/messages.txt") == 0)) echo "<p>There are no messages posted.</p>\n";}else { $MessageArray = file("MessageBoard/messages.txt"); echo "<table style=\"background-color:lightgray\" border=\"1\" width=\"100%\">\n"; $count = count($MessageArray);

324

Page 325: php_mysql Training

Manipulating Elements (continued)

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

325

Page 326: php_mysql Training

326

Manipulating Elements (continued)

Figure 6-2 Message Board page of the Message Board

Page 327: php_mysql Training

327

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

Page 328: php_mysql Training

328

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

Page 329: php_mysql Training

329

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

Page 330: php_mysql Training

330

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

Page 331: php_mysql Training

331

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

Page 332: php_mysql Training

332

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

Page 333: php_mysql Training

333

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

Page 334: php_mysql Training

334

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

Page 335: php_mysql Training

335

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

Page 336: php_mysql Training

336

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

Page 337: php_mysql Training

337

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

Page 338: php_mysql Training

338

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

Page 339: php_mysql Training

339

Removing Duplicate Elements (continued)

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

Page 340: php_mysql Training

340

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

Page 341: php_mysql Training

341

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

Page 342: php_mysql Training

342

Iterating Through an Array

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

Page 343: php_mysql Training

343

Iterating Through an Array (continued)

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

Page 344: php_mysql Training

344

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

Page 345: php_mysql Training

345

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

Page 346: php_mysql Training

346

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

Page 347: php_mysql Training

347

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

Page 348: php_mysql Training

348

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

Page 349: php_mysql Training

349

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

Page 350: php_mysql Training

350

Returning a Portion of an Array (continued)

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

Page 351: php_mysql Training

351

Sorting Arrays

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

Page 352: php_mysql Training

352

Sorting Arrays (continued)

Page 353: php_mysql Training

353

Sorting Arrays (continued)

Page 354: php_mysql Training

354

Sorting Arrays (continued)• If the sort() and rsort() functions are used

on an associative array, the keys are replaced with indexes

Page 355: php_mysql Training

355

Sorting Arrays (continued)

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

Page 356: php_mysql Training

356

Sorting Arrays (continued)

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

Page 357: php_mysql Training

357

Sorting Arrays (continued)

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

Page 358: php_mysql Training

358

Sorting Arrays (continued)

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

Page 359: php_mysql Training

359

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

Page 360: php_mysql Training

360

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

Page 361: php_mysql Training

361

Combining Arrays (continued)

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

Page 362: php_mysql Training

362

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

Page 363: php_mysql Training

363

Comparing Arrays (continued)

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

Page 364: php_mysql Training

364

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

Page 365: php_mysql Training

365

Comparing Arrays (continued)

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

Page 366: php_mysql Training

366

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

Page 367: php_mysql Training

367

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

Page 368: php_mysql Training

368

Creating Two-Dimensional Indexed Arrays (continued)

$Gallons = array( 128, // ounces 16, // cups 8, // pints 4 // quarts);

Page 369: php_mysql Training

369

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

Page 370: php_mysql Training

370

Creating Two-Dimensional Indexed Arrays (continued)

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

Page 371: php_mysql Training

371

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

Page 372: php_mysql Training

372

Creating Two-Dimensional Associative Arrays (continued)

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

Page 373: php_mysql Training

373

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

Page 374: php_mysql Training

374

Working with Additional Dimensions

Page 375: php_mysql Training

Using Arrays in Web Forms

• Store form data in an array by appending an opening and closing ([]) to the value of the name attribute

• Data from any element with the same value for the name attribute will be appended to an array with that name

375

Page 376: php_mysql Training

Using Arrays in Web Forms(continued)

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

value='submit' /></form>

376

Page 377: php_mysql Training

Using Arrays in Web Forms(continued)

if (is_array($_POST['answers')) { $Index = 0; foreach ($_POST['answers'] as $Answer) { ++$Index; echo "The answer for question $Index

is '$Answer'<br />\n"; }}

377

Page 378: php_mysql Training

Using Arrays in Web Forms(continued)

378

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

Page 379: php_mysql Training

Using Multidimensional Array Notation

• Multidimensional array notation can also be used to process posted form information

if (is_array($_POST['answers')) { $count = count($_POST['answers']); for ($i=0; $i<$count; ++$i) { echo "The answer for question " .

($i+1) . " is '{$_POST['answers'][$i]}'<br />\n";

}}

379

Page 380: php_mysql Training

Creating an Associative Forms Array

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

380

Page 381: php_mysql Training

381

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

Page 382: php_mysql Training

382

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

Page 383: php_mysql Training

383

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

Page 384: php_mysql Training

384

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

Page 385: php_mysql Training

385

Summary (continued)

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

Page 386: php_mysql Training

Chapter 7

Working with Databasesand MySQL

2nd Edition

Page 387: php_mysql Training

387

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

Page 388: php_mysql Training

388

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

Page 389: php_mysql Training

389

Introduction to Databases (continued)

Figure 7-1 Employee directory database

Page 390: php_mysql Training

390

Introduction to Databases (continued)

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

• A relational database stores information across multiple related tables

Page 391: php_mysql Training

391

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

Page 392: php_mysql Training

392

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

Page 393: php_mysql Training

393

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

Page 394: php_mysql Training

394

One-to-One Relationships (continued)

Figure 7-2 One-to-one relationship

Page 395: php_mysql Training

395

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

Page 396: php_mysql Training

396

One-to-Many Relationship (continued)

Figure 7-3 Table with redundant information

Page 397: php_mysql Training

397

One-to-Many Relationship (continued)

Figure 7-4 One-to-many relationship

Page 398: php_mysql Training

398

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

Page 399: php_mysql Training

399

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

Page 400: php_mysql Training

400

Working with Database Management Systems

(continued)

Figure 7-5 Many-to-many relationship

Page 401: php_mysql Training

401

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

Page 402: php_mysql Training

402

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

Page 403: php_mysql Training

Getting Started withMySQL

403

• 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

Page 404: php_mysql Training

404

Logging in to MySQL• Enter the following command:

mysql –h host –u user –p• Two accounts are created:

– Anonymous user account allows login without specifying a username or password

– root account (the primary administrative account for MySQL) is created without a password

mysql –u root

• Log out with the exit or quit commands

Page 405: php_mysql Training

405

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

Page 406: php_mysql Training

406

Logging in to MySQL (continued)

Figure 7-6 MySQL Monitor on a Windows platform

Page 407: php_mysql Training

408

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

Page 408: php_mysql Training

409

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

Page 409: php_mysql Training

410

Getting Help with MySQL Commands

Page 410: php_mysql Training

411

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

Page 411: php_mysql Training

412

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;

Page 412: php_mysql Training

413

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

Page 413: php_mysql Training

414

Defining Database Tables(continued)

Page 414: php_mysql Training

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]

415

Page 415: php_mysql Training

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

416

Page 416: php_mysql Training

Changing Table Field Names• Use the ALTER TABLE to change the name of an

existing field in a table using the following syntaxALTER TABLE table_name ADD [COLUMN] (column_name column_type [, column_name column_type ...]);

• In MySQL Monitor, enter the following:mysql> ALTER TABLE vehicles ADD COLUMN (model_year INT);[ENTER]

417

Page 417: php_mysql Training

Modifying Column Types• Use the ALTER TABLE to rename columns of an existing

field in a table using the following syntax

ALTER TABLE table_name CHANGE [COLUMN] column_name new_name column_type;

• In MySQL Monitor, enter the following:

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

418

Page 418: php_mysql Training

Renaming Columns• Use the ALTER TABLE to rename columns using the

following syntax

ALTER TABLE table_name MODIFY [COLUMN] column_name column_type;

In MySQL Monitor, enter the following:

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

419

Page 419: php_mysql Training

Renaming Tables• Use the ALTER TABLE to change the name of an

existing table using the following syntax

ALTER TABLE table_name RENAME [TO] new_name;

mysql> ALTER TABLE vehicles RENAME TO company_cars;[ENTER]

420

Page 420: php_mysql Training

Removing Columns• Use the ALTER TABLE to remove an existing field from a

table using the following syntax

ALTER TABLE table_name DROP [COLUMN] column_name;

mysql> ALTER TABLE company_cars DROP COLUMN assigned_to;[ENTER]

421

Page 421: php_mysql Training

Deleting Tables• Execute the DROP TABLE statement to remove all data and the

table definition from a databaseDROP TABLE table;

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

mysql> DROP TABLE company_cars;[ENTER]

• You must be logged in as the root user or have DROP privileges to delete a table.

422

Page 422: php_mysql Training

Modifying User Privileges• Privileges are actions and operations a user

can perform with a table or a database• For security purposes, user accounts should

only be assigned the minimum necessary privileges to perform given tasks

423

Page 423: php_mysql Training

Modifying User Privileges(continued)

424

Page 424: php_mysql Training

425

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

Page 425: php_mysql Training

426

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

Page 426: php_mysql Training

427

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

Page 427: php_mysql Training

428

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]

Page 428: php_mysql Training

Adding Records (continued)

• The LOAD DATA statement, with the full path and name of a local text file, is used to add multiple records to a table

LOAD DATA INFILE 'file_path' INTO TABLE table_name (column1, column2, …);

• Each record in the text file must be placed on a separate line with a tab delimiter between each field

429

Page 429: php_mysql Training

Adding Records (continued)

• If the column list is omitted, the values on each line must be in the same order you defined the table fields

• Use consecutive tabs with nothing between them to designate a column with no value

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

mysql> LOAD DATA INFILE 'company_cars.txt' INTO TABLE company_cars;[ENTER]

430

Page 430: php_mysql Training

Adding Records (continued)

• The optional FIELDS TERMINATED BY clause of the LOAD DATA statement allows you to change the field separator to a character such as (~ or ,) instead of the default tab character

• In MySQL Monitor, enter the following code at the mysql> prompt:mysql> LOAD DATA INFILE 'company_cars.txt‘ INTO TABLE company_cars;[ENTER]

431

Page 431: php_mysql Training

432

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

Page 432: php_mysql Training

433

Retrieving Records (continued)

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

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

Page 433: php_mysql Training

Using Aggregate Functions

• Aggregate functions summarize data in record sets rather than display the individual records

• The COUNT() function is unique in that– The wildcard (*) can be used as a function

argument instead of a field name– The keyword DISTINCT can be used after the

opening parentheses• The DISTINCT keyword can also be used with

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

434

Page 434: php_mysql Training

Using Aggregate Functions (continued)

• To retrieve aggregate values for groups of records, use the GROUP BY clause and include the fields that you use to group the records as part of the query

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

mysql> SELECT model_year, AVG(mileage) FROM company_cars GROUP BY model_year;[ENTER]

435

Page 435: php_mysql Training

436

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]

Page 436: php_mysql Training

437

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]

Page 437: php_mysql Training

438

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]

Page 438: php_mysql Training

439

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]

Page 439: php_mysql Training

440

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]

Page 440: php_mysql Training

441

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

Page 441: php_mysql Training

442

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]

Page 442: php_mysql Training

443

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

Page 443: php_mysql Training

444

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

Page 444: php_mysql Training

445

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

Page 445: php_mysql Training

446

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

Page 446: php_mysql Training

447

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

Page 447: php_mysql Training

448

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

Page 448: php_mysql Training

449

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

Page 449: php_mysql Training

450

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

Page 450: php_mysql Training

451

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

Page 451: php_mysql Training

452

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

Page 452: php_mysql Training

Chapter 8

Manipulating MySQLDatabases with PHP

2nd Edition

Page 453: php_mysql Training

454

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

Page 454: php_mysql Training

455

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

Page 455: php_mysql Training

456

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

Page 456: php_mysql Training

457

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

Page 457: php_mysql Training

458

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

Page 458: php_mysql Training

459

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

Page 459: php_mysql Training

460

Opening and Closing a MySQL Connection (continued)

Page 460: php_mysql Training

461

Opening and Closing a MySQL Connection (continued)

Figure 8-1 MySQLInfo.php in a Web browser

Page 461: php_mysql Training

462

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

Page 462: php_mysql Training

Reporting MySQL Errors (continued)

• The mysql_errno() function returns the error code from the last attempted MySQL function call or 0 if no error occurred

• The mysql_errno() and mysql_error() functions return the results of the previous mysql*() function

463

Page 463: php_mysql Training

464

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

Page 464: php_mysql Training

Creating a Database

• Use the mysql_create_db() function to create a new database

• The basic syntax for the mysql_create_db() is:$result = mysql_create_db( "dbname" [, connection]);

• The mysql_create_db() returns a Boolean TRUE if successful or FALSE if there was an error

465

Page 465: php_mysql Training

Creating a Database (continued)

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

466

Page 466: php_mysql Training

467

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

Page 467: php_mysql Training

Deleting a Database

• To delete a database, use the mysql_drop_db() function.

• The format for the mysql_drop_db() function is:$Result = mysql_drop_db("dbname" [, connection]);

• The function returns a value of TRUE if it successfully drops a database or FALSE if it does not

468

Page 468: php_mysql Training

469

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

Page 469: php_mysql Training

470

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

Page 470: php_mysql Training

Creating and Deleting Tables

• Use the CREATE TABLE statement with the mysql_query() function to create a new table

• Use the mysql_select_db() function before executing the CREATE TABLE statement to verify that you are in the right database

471

Page 471: php_mysql Training

Creating and Deleting Tables (continued)

$SQLstring = "CREATE TABLE drivers (name VARCHAR(100), "

. "emp_no SMALLINT, hire_date DATE, " . "stop_date DATE)";$QueryResult = @mysql_query($SQLstring, $DBConnect);if ($QueryResult===FALSE) echo "<p>Unable to execute the query.</p>" . "<p>Error code " .

mysql_errno($DBConnect) . ": " . mysql_error($DBConnect) .

"</p>";else echo "<p>Successfully created the table.</p>";

472

Page 472: php_mysql Training

Creating and Deleting Tables (continued)

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

473

Page 473: php_mysql Training

474

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

Page 474: php_mysql Training

Creating and Deleting Tables (continued)

• To identify a field as a primary key in MySQL, include the PRIMARY KEY keywords when you define a field with the CREATE TABLE statement

• The AUTO_INCREMENT keyword is often used with a primary key to generate a unique ID for each new row in a table

• The NOT NULL keywords are often used with primary keys to require that a field include a value

475

Page 475: php_mysql Training

Creating and Deleting Tables (continued)

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

476

Page 476: php_mysql Training

Adding, Deleting, and Updating Records

• To add records to a table, use the INSERT and VALUES keywords with the mysql_query() function

• To add multiple records to a database, use the LOAD DATA statement with the name of the local text file containing the records you want to add

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

477

Page 477: php_mysql Training

Adding, Deleting, and Updating Records (continued)

• The UPDATE keyword specifies the name of the table to update

• The SET keyword specifies the value to assign to the fields in the records that match the condition in the WHERE clause

• To delete records in a table, use the DELETE statement with the mysql_query() function

• Omit the WHERE clause to delete all records in a table

478

Page 478: php_mysql Training

479

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

Page 479: php_mysql Training

480

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

Page 480: php_mysql Training

481

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

Page 481: php_mysql Training

482

Using the mysql_affected_rows() Function (continued)

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

Page 482: php_mysql Training

483

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

Page 483: php_mysql Training

484

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

Page 484: php_mysql Training

485

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

}

Page 485: php_mysql Training

486

Using the mysql_info() Function (continued)

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

Page 486: php_mysql Training

487

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

Page 487: php_mysql Training

488

Using the mysql_info() Function (continued)

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

Page 488: php_mysql Training

Working with Query Results

489

Page 489: php_mysql Training

Retrieving Records into an Indexed Array

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

490

Page 490: php_mysql Training

Retrieving Records into an Indexed Array

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

491

Page 491: php_mysql Training

Retrieving Records into an Indexed Array

492

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

Page 492: php_mysql Training

493

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

Page 493: php_mysql Training

494

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

Page 494: php_mysql Training

495

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

Page 495: php_mysql Training

496

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

Page 496: php_mysql Training

497

Accessing Query Result Information (continued)

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

Page 497: php_mysql Training

498

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

Page 498: php_mysql Training

499

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

Page 499: php_mysql Training

500

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

Page 500: php_mysql Training

501

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

Page 501: php_mysql Training

502

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

Page 502: php_mysql Training

503

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.

Page 503: php_mysql Training

504

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

Page 504: php_mysql Training

505

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

Page 505: php_mysql Training

Chapter 9

Managing State Information

2nd Edition

Page 506: php_mysql Training

507

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

Page 507: php_mysql Training

508

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

Page 508: php_mysql Training

509

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

Page 509: php_mysql Training

510

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

Page 510: php_mysql Training

511

Understanding State Information (continued)

Figure 9-1 College Internship Available OpportunitiesWeb site page flow

Page 511: php_mysql Training

512

Understanding State Information (continued)

Figure 9-2 Registration/Log In Web page

Page 512: php_mysql Training

513

Understanding State Information (continued)

Figure 9-3 New Intern Registration Web pageafter successful registration

Page 513: php_mysql Training

514

Understanding State Information (continued)

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

Page 514: php_mysql Training

515

Understanding State Information (continued)

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

Page 515: php_mysql Training

516

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

Page 516: php_mysql Training

517

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

Page 517: php_mysql Training

518

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

Page 518: php_mysql Training

519

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

Page 519: php_mysql Training

520

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>

Page 520: php_mysql Training

521

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

Page 521: php_mysql Training

522

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

Page 522: php_mysql Training

523

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

Page 523: php_mysql Training

524

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

Page 524: php_mysql Training

525

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

Page 525: php_mysql Training

526

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

Page 526: php_mysql Training

527

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

<?phpsetcookie("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>...

Page 527: php_mysql Training

528

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

Page 528: php_mysql Training

529

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

Page 529: php_mysql Training

530

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

Page 530: php_mysql Training

531

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

Page 531: php_mysql Training

532

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

Page 532: php_mysql Training

533

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

Page 533: php_mysql Training

534

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

Page 534: php_mysql Training

535

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

Page 535: php_mysql Training

536

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

Page 536: php_mysql Training

537

Reading Cookies (continued)

• Use multidimensional array syntax to read each cookie valuesetcookie("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]}.";

Page 537: php_mysql Training

538

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

Page 538: php_mysql Training

539

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

Page 539: php_mysql Training

540

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_

Page 540: php_mysql Training

541

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

<?phpsession_start();...

Page 541: php_mysql Training

542

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

Page 542: php_mysql Training

543

Starting a Session (continued)<?phpsession_start();...?><p><a href='<?php echo "Occupation.php?PHPSESSID=" . session_id() ?>'>Occupation</a></p>

Page 543: php_mysql Training

544

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

Page 544: php_mysql Training

545

Working with Session Variables (continued)

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

Page 545: php_mysql Training

546

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

?>

Page 546: php_mysql Training

547

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 autoglobal3. Use the session_destroy() function to delete the session

Page 547: php_mysql Training

548

Deleting a Session (continued)<?phpsession_start();$_SESSION = array();session_destroy();?>

Page 548: php_mysql Training

549

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

Page 549: php_mysql Training

550

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.

Page 550: php_mysql Training

551

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

Page 551: php_mysql Training

552

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

Page 552: php_mysql Training

553

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

Page 553: php_mysql Training

554

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.

Page 554: php_mysql Training

555

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.

Page 555: php_mysql Training

556

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

Page 556: php_mysql Training

557

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