Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 1 Getting Started with PHP PHP Programming with MySQL

Similar presentations


Presentation on theme: "Chapter 1 Getting Started with PHP PHP Programming with MySQL"— Presentation transcript:

1 Chapter 1 Getting Started with PHP PHP Programming with MySQL

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

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

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

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

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

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

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

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

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

11 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 PHP Programming with MySQL

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

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

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

15 Creating Multiple Code Declaration Blocks (continued)
Figure Output of a document with two PHP script sections PHP Programming with MySQL

16 Creating Multiple Code Declaration Blocks (continued)
Figure 1-10 PHP Environment Information Web page PHP Programming with MySQL

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

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

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

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

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

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

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

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

25 Displaying Variables Figure 1-11 Output from an echo statement
that is passed text and a variable PHP Programming with MySQL

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

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

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

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

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

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

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, ) Exponential notation, or scientific notation, is a shortened format for writing very large numbers or numbers with many decimal places (2.0e11) PHP Programming with MySQL

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

34 Figure 1-17 Conceptual example of an array
Arrays An array contains a set of data represented by a single variable name Figure 1-17 Conceptual example of an array PHP Programming with MySQL

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] PHP Programming with MySQL

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

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

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 Output of elements in the $Provinces[] array PHP Programming with MySQL

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

40 Accessing Element Information (continued)
Figure 1-19 Output of the count() function PHP Programming with MySQL

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

42 Accessing Element Information (continued)
Figure Output of the $Provinces[ ] array with the print_r() function PHP Programming with MySQL

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

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

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

46 Building Expressions (continued)
PHP Programming with MySQL

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

48 Arithmetic Operators Arithmetic operators are used in PHP to perform mathematical calculations (+ - x ÷) PHP Programming with MySQL

49 Arithmetic Operators (continued)
Figure 1-22 Results of arithmetic expressions PHP Programming with MySQL

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 Division and modulus expressions PHP Programming with MySQL

51 Arithmetic Binary Operators
PHP Programming with MySQL

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

53 Arithmetic Unary Operators (continued)
Figure 1-24 Script that uses the prefix increment operator PHP Programming with MySQL

54 Arithmetic Unary Operators (continued)
Figure 1-25 Output of the prefix version of the student ID script PHP Programming with MySQL

55 Figure 1-26 Script that uses the postfix increment operator
Arithmetic Unary Operators (continued) Figure 1-26 Script that uses the postfix increment operator PHP Programming with MySQL

56 Arithmetic Unary Operators (continued)
Figure 1-27 Output of the postfix version of the student ID script PHP Programming with MySQL

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

58 Assignment Operators (continued)
PHP Programming with MySQL

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

60 Comparison and Conditional Operators (continued)
PHP Programming with MySQL

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

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 Output of a script with a conditional operator PHP Programming with MySQL

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

64 Special Operators PHP Programming with MySQL

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

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

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

68 Understanding Operator Precedence (continued)
PHP Programming with MySQL

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

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

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

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

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. PHP Programming with MySQL

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

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

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

77 Chapter 2 Functions and Control Structures PHP Programming with MySQL

78 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 PHP Programming with MySQL

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

80 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 PHP Programming with MySQL

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

82 Calling Functions function displayCompanyName($CompanyName) {
echo "<p>$CompanyName</p>"; } displayCompanyName("Course Technology"); Figure 2-1 Output of a call to a custom function PHP Programming with MySQL

83 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; } PHP Programming with MySQL

84 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. PHP Programming with MySQL

85 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 PHP Programming with MySQL

86 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 PHP Programming with MySQL

87 The global Keyword (continued)
<?php $GlobalVariable = "Global variable"; function scopeExample() { global $GlobalVariable; echo "<p>$GlobalVariable</p>"; } scopeExample(); ?> PHP Programming with MySQL

88 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 PHP Programming with MySQL

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

90 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 ( } ) PHP Programming with MySQL

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

92 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 PHP Programming with MySQL

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

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

95 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 PHP Programming with MySQL

96 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 PHP Programming with MySQL

97 switch Statements (continued)
The syntax for the switch statement is: switch (expression) { case label: statement(s); break; ... default: } PHP Programming with MySQL

98 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 PHP Programming with MySQL

99 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 (:) PHP Programming with MySQL

100 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 PHP Programming with MySQL

101 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 PHP Programming with MySQL

102 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 PHP Programming with MySQL

103 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 PHP Programming with MySQL

104 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 PHP Programming with MySQL

105 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 *= PHP Programming with MySQL

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

107 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); PHP Programming with MySQL

108 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); PHP Programming with MySQL

109 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 PHP Programming with MySQL

110 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 PHP Programming with MySQL

111 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); } PHP Programming with MySQL

112 for Statements (continued)
$FastFoods = array(" pizza”, " burgers ", " french fries ", " tacos ", " fried chicken "); for ($Count = 0; $Count < 5; ++$Count) { echo $FastFoods[$Count], " <br /> "; } Figure Output of fast foods script PHP Programming with MySQL

113 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; } PHP Programming with MySQL

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

115 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 Output of the foreach script with index values PHP Programming with MySQL

116 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 PHP Programming with MySQL

117 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 PHP Programming with MySQL

118 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 PHP Programming with MySQL

119 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 PHP Programming with MySQL

120 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  PHP Programming with MySQL

121 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 PHP Programming with MySQL

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

123 Chapter 3 Manipulating Strings PHP Programming with MySQL

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

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 variable echo "<PHP literal text string</p>"; $StringVariable = "<p>PHP literal text string</p>"; echo $StringVariable; A string must begin and end with a matching quotation mark (single or double) PHP Programming with MySQL

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

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

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

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

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

131 Adding Escape Characters and Sequences (continued)
The escape character combined with one or more other characters is an escape sequence PHP Programming with MySQL

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

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

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

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

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

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

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

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

140 Encoding and Decoding a String (continued)
The characters that are converted with the htmlspecialchars()function are: '&' (ampersand) becomes '&' '"' (double quote) becomes '"' when ENT_NOQUOTES is disabled. ''' (single quote) becomes ''' only when ENT_QUOTES is enabled. '<' (less than) becomes '<' '>' (greater than) becomes '>' PHP Programming with MySQL

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

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

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

144 Other Ways to Manipulate a String (continued)
The substr()function returns part of a string based on the values of the start and length parameters The syntax for the substr() function is: substr(string, start, optional length); A positive number in the start parameter indicates how many character to skip at the beginning of the string A negative number in the start parameter indicates how many characters to count in from the end of the string PHP Programming with MySQL

145 Other Ways to Manipulate a String (continued)
A positive value in the in the length parameter determines how many characters to return A negative value in the length parameter skip that many characters at the end of the string and returns the middle portion If the length is omitted or is greater than the remaining length of the string, the entire remainder of the string is returned PHP Programming with MySQL

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

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

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

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

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

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 $ = $New = str_replace("president", "vice.president", $ ); echo $New ; // prints PHP Programming with MySQL

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

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 Output of a script that uses the strtok() function PHP Programming with MySQL

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 Output of a script with a strtok() function that uses two separators PHP Programming with MySQL

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

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

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

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

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

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 Output of a string created with the implode() function PHP Programming with MySQL

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>"; else echo "<p>The second letter is lower in the alphabet than The first letter.</p>"; PHP Programming with MySQL

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”) PHP Programming with MySQL

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

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

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

166 Determining the Similarity of Two Strings (continued)
Figure 3-20 Output of a script with the similar_text() and levenshtein() functions PHP Programming with MySQL

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

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>"; else echo "<p>The names are not pronounced the same.</p>"; PHP Programming with MySQL

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

170 Working with Regular Expressions (continued)
PHP Programming with MySQL

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

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 (/) PHP Programming with MySQL

173 Writing Regular Expression Patterns (continued)
PHP Programming with MySQL

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

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 = " preg_match("/^http/", $URL); // returns 1 PHP Programming with MySQL

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 = " eregi("^http", $URL); // returns 1; To specify an anchor at the end of a line, the pattern must end with the $ metacharacter $Identifier = " eregi("com$", $Identifier); // returns 1 PHP Programming with MySQL

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 = preg_match("/gov$/", $Identifier);//returns 0 PHP Programming with MySQL

178 Specifying Quantity Metacharacters that specify the quantity of a match are called quantifiers PHP Programming with MySQL

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 = " preg_match("/^https?/", $URL); // returns 1 PHP Programming with MySQL

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

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

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: ");// returns 1 PHP Programming with MySQL

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) preg_match("/^(1 )?(\(.{3}\) )?(.{3})(\.{4})$/ PHP Programming with MySQL

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 1 preg_match("/analy[sz]e/", "analyze");//returns 1 preg_match("/analy[sz]e/", "analyce");//returns 0 PHP Programming with MySQL

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

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

187 Defining Character Classes (continued)
PHP Programming with MySQL

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

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

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

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

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

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

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

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

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

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

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

199 Chapter 4 Handling User Input PHP Programming with MySQL

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

201 Using Autoglobals Autoglobals are predefined global arrays that provide information about server, environment, and user input PHP Programming with MySQL

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

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

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=" HandleFormInput.php"> PHP Programming with MySQL

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

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

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

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 (+) PHP Programming with MySQL

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) PHP Programming with MySQL

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

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

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

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

214 Handling Special Characters (continued)
PHP Programming with MySQL

215 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) PHP Programming with MySQL

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 address was entered in the correct format the user did not exceed the word limit in a comment box PHP Programming with MySQL

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

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 must be validated PHP Programming with MySQL

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

220 Validating String Data
Regular expression functions are some of the best tools for verifying that string data meets the strict formatting required for 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 PHP Programming with MySQL

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

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

223 ing the Web Form The mail() function is used to send an 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 addresses that can be entered as the recipient argument Plain address: Recipients name and address: Mary Smith PHP Programming with MySQL

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 editors – From, Cc, Bcc and Date. PHP Programming with MySQL

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 element Date: Fri, 03 Apr :05: From: Linda M. Jones CC: Mary R. Jones A successful message returns a value of TRUE PHP Programming with MySQL

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

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 set if (isset($Submit)) { // Validate the data } The argument of the isset() function is the name assigned to the Submit button in the Web form PHP Programming with MySQL

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 validation if (isset ($_POST['Submit'])) { // Process the data } else { // Display the Web form PHP Programming with MySQL

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

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

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

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” PHP Programming with MySQL

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

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 page include('inc_home.html'); default: } PHP Programming with MySQL

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

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

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

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

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

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

241 Summary (continued) The mail() function is used to send mail from PHP; it can be used to send form data via 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) PHP Programming with MySQL

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

243 Chapter 5 Working with Files and Directories PHP Programming with MySQL

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

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

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

247 Understanding File Types (continued)
PHP Programming with MySQL

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. PHP Programming with MySQL

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

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) PHP Programming with MySQL

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

252 Working with File Permissions (continued)
PHP Programming with MySQL

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

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

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

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

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

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

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

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

261 Reading Directories (continued)
Figure 5-3 Listing of the “files” subdirectory using the scandir() function PHP Programming with MySQL

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

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

264 Creating Directories (continued)
Figure 5-4 Warning that appears if a directory already exists PHP Programming with MySQL

265 Obtaining File and Directory Information
PHP Programming with MySQL

266 Obtaining File and Directory Information (continued)
PHP Programming with MySQL

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 not exist.</p>"; PHP Programming with MySQL

268 Obtaining File and Directory Information (continued)
Figure 5-5 Output of script with file and directory information functions PHP Programming with MySQL

269 Obtaining File and Directory Information (continued)
The following table returns additional information about files and directories: PHP Programming with MySQL

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

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

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

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

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'] PHP Programming with MySQL

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

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. PHP Programming with MySQL

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

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

279 Downloading Files (continued)
PHP Programming with MySQL

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

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]) PHP Programming with MySQL

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

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

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

285 Reading an Entire File PHP Programming with MySQL

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 to mid 70s. West winds 5 to 15 mph. Tonight: Increasing clouds. Lows in the mid 40s to lower 50s. West winds 5 to 10 mph.</p>"; file_put_contents("sfweather.txt", $DailyForecast); $SFWeather = file_get_contents("sfweather.txt"); echo $SFWeather; PHP Programming with MySQL

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

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

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

290 Reading an Entire File (continued)
Figure Output of individual lines in a text file PHP Programming with MySQL

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 resource 1. Open the file stream with the fopen() function 2. Write data to or read data from the file stream 3. Close the file stream with the fclose() function PHP Programming with MySQL

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

293 Opening a File Stream (continued)
PHP Programming with MySQL

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+” PHP Programming with MySQL

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+” PHP Programming with MySQL

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

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

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) PHP Programming with MySQL

299 Reading Data Incrementally
The fgets() function uses the file pointer to iterate through a text file PHP Programming with MySQL

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

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

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

303 Copying and Moving Files (continued)
if (file_exists(" sfweather.txt ")) { if(is_dir(" history ")) { if (copy(" sfweather.txt ", " history\\sfweather txt ")) echo " <p>File copied successfully.</p> "; else echo " <p>Unable to copy the file!</p> "; } echo (" <p>The directory does not exist!</p> "); echo (" <p>The file does not exist!</p> "); PHP Programming with MySQL

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) PHP Programming with MySQL

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

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

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

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

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

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

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

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

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

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

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

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

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

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

319 Chapter 6 Manipulating Arrays PHP Programming with MySQL

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

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

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> <a href="MessageBoard.php">View Messages</a> PHP Programming with MySQL

323 Manipulating Elements (continued)
Figure 6-1 Post New Message page of the Message Board PHP Programming with MySQL

324 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); PHP Programming with MySQL

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

326 Manipulating Elements (continued)
Figure 6-2 Message Board page of the Message Board PHP Programming with MySQL

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

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

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

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

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

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

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

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

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

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]); PHP Programming with MySQL

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

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

339 Removing Duplicate Elements (continued)
Figure 6-4 Output of an array after removing duplicate values with the array_unique() function PHP Programming with MySQL

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

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

342 Iterating Through an Array
The internal array pointer refers to the currently selected element in an array PHP Programming with MySQL

343 Iterating Through an Array (continued)
Figure 6-8 Output of an array without advancing the internal array pointer PHP Programming with MySQL

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

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

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

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

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

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

350 Returning a Portion of an Array (continued)
Figure 6-11 Output of an array returned with the array_slice() function PHP Programming with MySQL

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

352 Sorting Arrays (continued)
PHP Programming with MySQL

353 Sorting Arrays (continued)
PHP Programming with MySQL

354 Sorting Arrays (continued)
If the sort() and rsort() functions are used on an associative array, the keys are replaced with indexes PHP Programming with MySQL

355 Sorting Arrays (continued)
Figure 6-12 Output of an array after applying the sort() and rsort() functions PHP Programming with MySQL

356 Sorting Arrays (continued)
Figure 6-13 Output of an associative array after sorting with the sort() function PHP Programming with MySQL

357 Sorting Arrays (continued)
Figure 6-14 Output of an associative array after sorting with the asort() function PHP Programming with MySQL

358 Sorting Arrays (continued)
Figure 6-15 Output of an associative array after sorting with the ksort() function PHP Programming with MySQL

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, ...); PHP Programming with MySQL

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

361 Combining Arrays (continued)
Figure 6-12 Output of two indexed arrays combined with the addition operator PHP Programming with MySQL

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

363 Comparing Arrays (continued)
The syntax for the array_intersect() function is: new_array = array_intersect($array1, $array2, $array3, ...); PHP Programming with MySQL

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

365 Comparing Arrays (continued)
Figure 6-20 Output of an array created with the array_intersect() function PHP Programming with MySQL

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

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

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

369 Creating Two-Dimensional Indexed Arrays (continued)
$Ounces = array(1, 0.125, , , ); $Cups = array(8, 1, 0.5, 0.25, ); $Pints = array(16, 2, 1, 0.5, 0.125); $Quarts = array(32, 4, 2, 1, 0.25); $Gallons = array(128, 16, 8, 4, 1); PHP Programming with MySQL

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

371 Creating Two-Dimensional Associative Arrays
$Ounces = array("ounces" => 1, "cups" => 0.125, "pints" => , "quarts" => , "gallons" => ); $Cups = array("ounces" => 8, "cups" => 1, "pints" =>0.5, "quarts" => 0.25, "gallons" => ); $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); PHP Programming with MySQL

372 Creating Two-Dimensional Associative Arrays (continued)
Figure 6-21 Elements and keys in the $VolumeConversions[ ] array PHP Programming with MySQL

373 Creating Multidimensional Arrays with a Single Statement
$VolumeConversions = array( array(1, 0.125, , , ), // Ounces array(8, 1, 0.5, 0.25, ), // 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 ); PHP Programming with MySQL

374 Working with Additional Dimensions
PHP Programming with MySQL

375 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 PHP Programming with MySQL

376 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: <p>Enter the third answer: <input type='submit' name='submit' value='submit' /> </form> PHP Programming with MySQL

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

378 Using Arrays in Web Forms (continued)
Figure 6-22 Output of an array posted from a Web form PHP Programming with MySQL

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

380 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> PHP Programming with MySQL

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

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

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

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

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

386 Chapter 7 Working with Databases and MySQL
PHP Programming with MySQL

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

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

389 Introduction to Databases (continued)
Figure 7-1 Employee directory database PHP Programming with MySQL

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

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

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

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

394 One-to-One Relationships (continued)
Figure 7-2 One-to-one relationship PHP Programming with MySQL

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

396 One-to-Many Relationship (continued)
Figure 7-3 Table with redundant information PHP Programming with MySQL

397 One-to-Many Relationship (continued)
Figure 7-4 One-to-many relationship PHP Programming with MySQL

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

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

400 Working with Database Management Systems (continued)
Figure 7-5 Many-to-many relationship PHP Programming with MySQL

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

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

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

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

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: 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 PHP Programming with MySQL

406 Logging in to MySQL (continued)
Figure 7-6 MySQL Monitor on a Windows platform PHP Programming with MySQL

407 Working with the MySQL Monitor
At the mysql> command prompt terminate the command with a semicolon mysql> SELECT * FROM inventory; Without a semicolon, the MySQL Monitor enters a multiple-line command and changes the prompt to -> mysql> SELECT * FROM inventory -> The SQL keywords entered in the MySQL Monitor are not case sensitive PHP Programming with MySQL

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

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

410 Getting Help with MySQL Commands
PHP Programming with MySQL

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

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 database mysql> DROP DATABASE database; PHP Programming with MySQL

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

414 Defining Database Tables (continued)
PHP Programming with MySQL

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

416 Viewing Table Structure
Use the DESCRIBE table_name statement to view the structure of the table PHP Programming with MySQL

417 Changing Table Field Names
Use the ALTER TABLE to change the name of an existing field in a table using the following syntax ALTER TABLE table_name ADD [COLUMN] (column_name column_type [, column_name column_type ...]); In MySQL Monitor, enter the following: mysql> ALTER TABLE vehicles ADD COLUMN (model_year INT);[ENTER] PHP Programming with MySQL

418 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] PHP Programming with MySQL

419 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] PHP Programming with MySQL

420 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] PHP Programming with MySQL

421 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] PHP Programming with MySQL

422 Deleting Tables Execute the DROP TABLE statement to remove all data and the table definition from a database DROP TABLE table; In MySQL Monitor, enter the following at the mysql> prompt: mysql> DROP TABLE company_cars;[ENTER] You must be logged in as the root user or have DROP privileges to delete a table. PHP Programming with MySQL

423 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 PHP Programming with MySQL

424 Modifying User Privileges (continued)
PHP Programming with MySQL

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

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

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

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', );[ENTER] PHP Programming with MySQL

429 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 PHP Programming with MySQL

430 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] PHP Programming with MySQL

431 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] PHP Programming with MySQL

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

433 Retrieving Records (continued)
In MySQL Monitor, enter the following code at the mysql> prompt: mysql> SELECT model, mileage FROM company_cars;[ENTER] PHP Programming with MySQL

434 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 PHP Programming with MySQL

435 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] PHP Programming with MySQL

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] PHP Programming with MySQL

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] PHP Programming with MySQL

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] PHP Programming with MySQL

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] PHP Programming with MySQL

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] PHP Programming with MySQL

441 Updating Records To update records in a table, use the UPDATE statement The syntax for the UPDATE statement is: UPDATE table_name SET column_name=value WHERE condition; The UPDATE keyword specifies the name of the table to update The SET keyword specifies the value to assign to the fields in the records that match the condition in the WHERE keyword PHP Programming with MySQL

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] PHP Programming with MySQL

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

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

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

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

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

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

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

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

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

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

453 Chapter 8 Manipulating MySQL Databases with PHP PHP Programming with MySQL

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

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

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 and later Earlier versions must use the mysql package The mysqli package is the object-oriented equivalent of the mysql package PHP Programming with MySQL

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

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

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

460 Opening and Closing a MySQL Connection (continued)
PHP Programming with MySQL

461 Opening and Closing a MySQL Connection (continued)
Figure 8-1 MySQLInfo.php in a Web browser PHP Programming with MySQL

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

463 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 PHP Programming with MySQL

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

465 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 PHP Programming with MySQL

466 Creating a Database (continued)
Figure 8-2 Error message when the mysql_create_db() function is unavailable because of insufficient privileges PHP Programming with MySQL

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

468 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 PHP Programming with MySQL

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

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

471 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 PHP Programming with MySQL

472 Creating and Deleting Tables (continued)
$SQLstring = "CREATE TABLE drivers (name VARCHAR(100), " . "emp_no SMALLINT, hire_date DATE, " . "stop_date DATE)"; $QueryResult $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>"; PHP Programming with MySQL

473 Creating and Deleting Tables (continued)
Figure 8-3 Error code and message that displays when you attempt to create a table that already exists PHP Programming with MySQL

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 $DBConnect); PHP Programming with MySQL

475 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 PHP Programming with MySQL

476 Creating and Deleting Tables (continued)
To delete a table, use the DROP TABLE statement with the mysql_query() function PHP Programming with MySQL

477 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 PHP Programming with MySQL

478 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 PHP Programming with MySQL

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 row echo "<table width='100%‘ border='1'>"; echo "<tr><th>Make</th><th>Model</th> <th>Price</th><th>Quantity</th></tr>"; $Row = mysql_fetch_row($QueryResult); do { echo "<tr><td>{$Row[0]}</td>"; echo "<td>{$Row[1]}</td>"; echo "<td align='right'>{$Row[2]}</td>"; echo "<td align='right'>{$Row[3]}</td></tr>"; } while ($Row); PHP Programming with MySQL

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

481 Using the mysql_affected_rows() Function (continued)
$SQLstring = "UPDATE company_cars SET mileage= WHERE license='AK-1234'"; $QueryResult $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>"; PHP Programming with MySQL

482 Using the mysql_affected_rows() Function (continued)
Figure 8-5 Output of mysql_affected_rows() function for an UPDATE query PHP Programming with MySQL

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

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

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

486 Using the mysql_info() Function (continued)
Figure 8-6 Output of mysql_info() function for an INSERT query that adds multiple records PHP Programming with MySQL

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

488 Using the mysql_info() Function (continued)
Figure 8-7 Output of mysql_info() function for a LOAD DATA query PHP Programming with MySQL

489 Working with Query Results
PHP Programming with MySQL

490 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 PHP Programming with MySQL

491 Retrieving Records into an Indexed Array
$SQLstring = "SELECT * FROM company_cars"; $QueryResult $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"; PHP Programming with MySQL

492 Retrieving Records into an Indexed Array
Figure 8-8 Output of the company_cars table in a Web Browser PHP Programming with MySQL

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

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

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

496 Accessing Query Result Information (continued)
$SQLstring = "SELECT * FROM company_cars"; $QueryResult $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>"; echo "<p>Your query returned no results.</p>"; mysql_close($DBConnect); PHP Programming with MySQL

497 Accessing Query Result Information (continued)
Figure 8-10 Output of the number of rows and fields returned from a query PHP Programming with MySQL

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

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

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

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

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

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. PHP Programming with MySQL

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

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

506 Chapter 9 Managing State Information PHP Programming with MySQL

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

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

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

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

511 Understanding State Information (continued)
Figure 9-1 College Internship Available Opportunities Web site page flow PHP Programming with MySQL

512 Understanding State Information (continued)
Figure 9-2 Registration/Log In Web page PHP Programming with MySQL

513 Understanding State Information (continued)
Figure 9-3 New Intern Registration Web page after successful registration PHP Programming with MySQL

514 Understanding State Information (continued)
Figure 9-4 Verify Login Web Page for a successful login PHP Programming with MySQL

515 Understanding State Information (continued)
Figure 9-5 The Available Opportunities Web page with the Intern information at top of screen PHP Programming with MySQL

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

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

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

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

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=" .php?firstName=Don&lastName=Gosselin& occupation=writer">Link Text</a> PHP Programming with MySQL

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

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

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

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

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

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

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 <?php setcookie("firstName", "Don"); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" " <html xmlns=" <head> <title>College Internships</title> ... PHP Programming with MySQL

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

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

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

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

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 path setcookie("firstName", "Don", time()+3600, "/marketing/"); PHP Programming with MySQL

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 domain setcookie("firstName", "Don”, time()+3600, "/", ".gosselin.com"); PHP Programming with MySQL

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

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

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']}."; PHP Programming with MySQL

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

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

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

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: f39d7dd020773f115d753c71290e11f The session_start() function creates a text file on the Web server that is the same name as the session ID, preceded by sess_ PHP Programming with MySQL

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 <?php session_start(); ... PHP Programming with MySQL

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

543 Starting a Session (continued)
<?php session_start(); ... ?> <p><a href='<?php echo "Occupation.php?PHPSESSID=" . session_id() ?>'>Occupation</a></p> PHP Programming with MySQL

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

545 Working with Session Variables (continued)
<?php session_start(); $_SESSION['firstName'] = "Don"; $_SESSION['lastName'] = "Gosselin"; $_SESSION['occupation'] = "writer"; ?> <p><a href='<?php echo "Occupation.php?" . session_id() ?>'>Occupation</a></p> PHP Programming with MySQL

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

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 autoglobal 3. Use the session_destroy() function to delete the session PHP Programming with MySQL

548 Deleting a Session (continued)
<?php session_start(); $_SESSION = array(); session_destroy(); ?> PHP Programming with MySQL

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

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. PHP Programming with MySQL

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

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

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

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. PHP Programming with MySQL

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. PHP Programming with MySQL

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

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

558 Chapter 10 Developing Object-Oriented PHP PHP Programming with MySQL

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

560 Introduction to Object-Oriented Programming
Object-oriented programming (OOP) refers the concept of merging related variables and functions into a single interface An object refers to programming code and data that can be treated as an individual unit or component Objects are often also called components PHP Programming with MySQL

561 Introduction to Object-Oriented Programming (continued)
Data refers to information contained within variables or other types of storage structures The functions associated with an object are called methods The variables that are associated with an object are called properties or attributes Popular object-oriented programming languages include C++, Java, and Visual Basic PHP Programming with MySQL

562 Introduction to Object-Oriented Programming (continued)
Figure 10-1 Accounting program PHP Programming with MySQL

563 Understanding Encapsulation
Objects are encapsulated – all code and required data are contained within the object itself Encapsulated objects hide all internal code and data An interface refers to the methods and properties that are required for a source program to communicate with an object PHP Programming with MySQL

564 Understanding Encapsulation (continued)
Encapsulated objects allow users to see only the methods and properties of the object that you allow them to see Encapsulation reduces the complexity of the code Encapsulation prevents other programmers from accidentally introducing a bug into a program, or stealing code PHP Programming with MySQL

565 Object-Oriented Programming and Classes
The code, methods, attributes, and other information that make up an object are organized into classes An instance is an object that has been created from an existing class Creating an object from an existing class is called instantiating the object An object inherits its methods and properties from a class — it takes on the characteristics of the class on which it is based PHP Programming with MySQL

566 Using Objects in PHP Scripts
Declare an object in PHP by using the new operator with a class constructor A class constructor is a special function with the same name as its class that is called automatically when an object from the class is instantiated The syntax for instantiating an object is: $ObjectName = new ClassName(); PHP Programming with MySQL

567 Using Objects in PHP Scripts (continued)
After an object is instantiated, use a hyphen and a greater-than symbol (->) to access the methods and properties contained in the object Together, these two characters are referred to as member selection notation With member selection notation, one or more characters are appended to an object, followed by the name of a method or property PHP Programming with MySQL

568 Using Objects in PHP Scripts (continued)
With methods, include a set of parentheses at the end of the method name, just as with functions Like functions, methods can also accept arguments $Checking->getBalance(); $CheckNumber = 1022; $Checking->getCheckAmount($CheckNumber); PHP Programming with MySQL

569 Working with Database Connections as Objects
Access MySQL database connections as objects by instantiating an object from the mysqli class To connect to a MySQL database server using procedural syntax: $DBConnect = mysql_connect("php_db", "dongosselin", "rosebud"); mysql_select_db("real_estate", $DBConnect); To connect to the MySQL database server using object-oriented style: $DBConnect = new mysqli("php_db", "dongosselin", "rosebud", "real_estate"); PHP Programming with MySQL

570 Handling MySQL Errors This statement uses the mysqli() constructor function to instantiate a mysqli class object named $DBConnect $DBConnect mysqli("php_db", "dgosselin", "rosebud"); To explicitly close the database connection, use the close() method of the mysqli class $DBConnect->close(); PHP Programming with MySQL

571 Handling MySQL Errors (continued)
With object-oriented style, check whether a value is assigned to the mysqli_connect_errno() or mysqli_connect_error() functions $DBConnect mysqli("php.db", "dgosselin", "rosebud"); if ($DBConnect->connect_errno){ echo("<p>Unable to connect to the database server.</p>" . "<p>Error code " . $DBConnect->connect_errno . ": " . $DBConnect->connect_error. "</p>\n"; else { //code to execute if the connection fails } PHP Programming with MySQL

572 Executing SQL Statements
With object-oriented style, use the query() method of the mysqli class To return the fields in the current row of a resultset into an indexed array use: The fetch_row() method of the mysqli class To return the fields in the current row of a resultset into an associative array use: The fetch_assoc() method of the msqli class PHP Programming with MySQL

573 Executing SQL Statements (continued)
$TableName = "company_cars"; $SQLstring = "SELECT * FROM $TableName"; $QueryResult if ($QueryResult === FALSE) echo "<p>Unable to execute the query. " . "Error code " . $DBConnect->errno . ": " . $DBConnect->error . "</p>\n"; else { echo "<table width='100%' border='1'>\n"; echo "<tr><th>License</th><th>Make</th><th>Model</th>" . "<th>Mileage</th><th>Year</th></tr>\n"; PHP Programming with MySQL

574 Executing SQL Statements (continued)
while (($Row = $QueryResult->fetch_row()) !== FALSE) { echo "<tr><td>{$Row[0]}</td>"; echo "<td>{$Row[1]}</td>"; echo "<td>{$Row[2]}</td>"; echo "<td align='right'>{$Row[3]}</td>"; echo "<td>{$Row[4]}</td></tr>\n"; } echo "</table>\n"; PHP Programming with MySQL

575 Defining Custom PHP Classes
Data structure refers to a system for organizing data The functions and variables defined in a class are called class members Class variables are referred to as data members or member variables Class functions are referred to as member functions or function members PHP Programming with MySQL

576 Defining Custom PHP Classes (continued)
Help make complex programs easier to manage Hide information that users of a class do not need to access or know about Make it easier to reuse code or distribute your code to others for use in their programs Inherited characteristics allow you to build new classes based on existing classes without having to rewrite the code contained in the existing one PHP Programming with MySQL

577 Creating a Class Definition
To create a class in PHP, use the class keyword to write a class definition A class definition contains the data members and member functions that make up the class The syntax for defining a class is: class ClassName { data member and member function definitions } PHP Programming with MySQL

578 Creating a Class Definition (continued)
The ClassName portion of the class definition is the name of the new class Class names usually begin with an uppercase letter to distinguish them from other identifiers Within the class’s curly braces, declare the data type and field names for each piece of information stored in the structure class BankAccount { data member and member function definitions } $Checking = new BankAccount(); PHP Programming with MySQL

579 Creating a Class Definition (continued)
Class names in a class definition are not followed by parentheses, as are function names in a function definition $Checking = new BankAccount(); echo 'The $Checking object is instantiated from the ' . get_class($Checking) . " class.</p>"; Use the instanceof operator to determine whether an object is instantiated from a given class Use the class_exists() to determine if a class exists PHP Programming with MySQL

580 Storing Classes in External Files
PHP provides the following functions that allow you to use external files in your PHP scripts: include() require() include_once() require_once() You pass to each function the name and path of the external file you want to use PHP Programming with MySQL

581 Storing Classes in External Files (continued)
include() and require() functions both insert the contents of an external file, called an include file, into a PHP script include_once() and require_once() functions only include an external file once during the processing of a script Any PHP code must be contained within a PHP script section (<?php ... ?>) in an external file PHP Programming with MySQL

582 Collecting Garbage Garbage collection refers to cleaning up or reclaiming memory that is reserved by a program PHP knows when your program no longer needs a variable or object and automatically cleans up the memory for you The one exception is with open database connections PHP Programming with MySQL

583 Information Hiding Information hiding states that any class members that other programmers, sometimes called clients, do not need to access or know about should be hidden Helps minimize the amount of information that needs to pass in and out of an object Reduces the complexity of the code that clients see Prevents other programmers from accidentally introducing a bug into a program by modifying a class’s internal workings PHP Programming with MySQL

584 Using Access Specifiers
Access specifiers control a client’s access to individual data members and member functions There are three levels of access specifiers in PHP: public, private, and protected The public access specifier allows anyone to call a class’s member function or to modify and retrieve a data member PHP Programming with MySQL

585 Using Access Specifiers (continued)
The private access specifier prevents clients from calling member functions or accessing data members and is one of the key elements in information hiding Private access does not restrict a class’s internal access to its own members Private access restricts clients from accessing class members PHP Programming with MySQL

586 Using Access Specifiers (continued)
Include an access specifier at the beginning of a data member declaration statement class BankAccount { public $Balance = 0; } Always assign an initial value to a data member when you first declare it public $Balance = 1 + 2; PHP Programming with MySQL

587 Serializing Objects Serialization refers to the process of converting an object into a string that you can store for reuse Serialization stores both data members and member functions into strings To serialize an object, pass an object name to the serialize() function $SavedAccount = serialize($Checking); PHP Programming with MySQL

588 Serializing Objects (continued)
To convert serialized data back into an object, you use the unserialize() function $Checking = unserialize($SavedAccount); Serialization is also used to store the data in large arrays To use serialized objects between scripts, assign a serialized object to a session variable session_start(); $_SESSION('SavedAccount') = serialize($Checking); PHP Programming with MySQL

589 Working with Member Functions
Create public member functions for any functions that clients need to access Create private member functions for any functions that clients do not need to access Access specifiers control a client’s access to individual data members and member functions PHP Programming with MySQL

590 Working with Member Functions (continued)
class BankAccount { public $Balance = ; public function withdrawal($Amount) { $this->Balance -= $Amount; } if (class_exists("BankAccount")) $Checking = new BankAccount(); else exit("<p>The BankAccount class is not available!</p>"); printf("<p>Your checking account balance is $%.2f.</p>", $Checking->Balance); $Cash = 200; $Checking->withdrawal(200); printf("<p>After withdrawing $%.2f, your checking account balance is $%.2f.</p>", $Cash, $Checking->Balance); PHP Programming with MySQL

591 Using the $this Reference
Outside of a class, refer to the members of the object using the name of the object, the member selection nation (-), and the name of the function or variable Within a class function definition, use $this to refer to the current object of the class $this->AccountNumber = 0; PHP Programming with MySQL

592 Initializing with Constructor Functions
A constructor function is a special function that is called automatically when an object from a class is instantiated class BankAccount { private $AccountNumber; private $CustomerName; private $Balance; function __construct() { $this->AccountNumber = 0; $this->Balance = 0; $this->CustomerName = ""; } PHP Programming with MySQL

593 Initializing with Constructor Functions (continued)
The __construct() function takes precedence over a function with the same name as the class Constructor functions are commonly used in PHP to handle database connection tasks PHP Programming with MySQL

594 Cleaning Up with Destructor Functions
A default constructor function is called when a class object is first instantiated A destructor function is called when the object is destroyed A destructor function cleans up any resources allocated to an object after the object is destroyed PHP Programming with MySQL

595 Cleaning Up with Destructor Functions (continued)
A destructor function is commonly called in two ways: When a script ends When you manually delete an object with the unset() function To add a destructor function to a PHP class, create a function named __destruct() PHP Programming with MySQL

596 Cleaning Up with Destructor Functions (continued)
function __construct() { $DBConnect = new mysqli("php_db", "dongosselin","rosebud", "real_estate"); } function __destruct() { $DBConnect->close(); PHP Programming with MySQL

597 Writing Accessor Functions
Accessor functions are public member functions that a client can call to retrieve or modify the value of a data member Accessor functions often begin with the words “set” or “get” Set functions modify data member values Get functions retrieve data member values PHP Programming with MySQL

598 Writing Accessor Functions (continued)
class BankAccount { private $Balance = 0; public function setBalance($NewValue) { $this->Balance = $NewValue; } public function getBalance() { return $this->Balance; if (class_exists("BankAccount")) $Checking = new BankAccount(); else exit("<p>The BankAccount class is not available!</p>"); $Checking->setBalance(100); echo "<p>Your checking account balance is " . $Checking->getBalance() . "</p>\n"; PHP Programming with MySQL

599 Serialization Functions
When you serialize an object with the serialize() function, PHP looks in the object’s class for a special function named __sleep() The primary reason for including a __sleep() function in a class is to specify which data members of the class to serialize PHP Programming with MySQL

600 Serialization Functions (continued)
If you do not include a __sleep() function in your class, the serialize() function serializes all of its data members function __sleep() { $SerialVars = array('Balance'); return $SerialVars; } When the unserialize() function executes, PHP looks in the object’s class for a special function named __wakeup() PHP Programming with MySQL

601 Summary The term “object-oriented programming (OOP)” refers to the creation of reusable software objects that can be easily incorporated into multiple programs. The term “object” specifically refers to programming code and data that can be treated as an individual unit or component (object) The term “data” refers to information contained within variables or other types of storage structures PHP Programming with MySQL

602 Summary (continued) The functions associated with an object are called methods, and the variables associated with an object are called properties or attributes Objects are encapsulated, which means that all code and required data are contained within the object itself An interface represents elements required for a source program to communicate with an object PHP Programming with MySQL

603 Summary (continued) In object-oriented programming, the code, methods, attributes, and other information that make up an object are organized into classes An instance is an object that has been created from an existing class. When you create an object from an existing class, you are “instantiating the object” PHP Programming with MySQL

604 Summary (continued) A particular instance of an object inherits its methods and properties from a class—that is, it takes on the characteristics of the class on which it is based A constructor is a special function with the same name as its class; it is called automatically when an object from the class is instantiated The term “data structure” refers to a system for organizing data PHP Programming with MySQL

605 Summary (continued) The functions and variables defined in a class are called class members. Class variables are referred to as data members or member variables, whereas class functions are referred to as member functions or function members A class definition contains the data members and member functions that make up the class PHP Programming with MySQL

606 Summary (continued) PHP provides the following functions that allow you to use external files in your PHP scripts: include(), require(), include_once(), and require_once() The principle of information hiding states that class members should be hidden when other programmers do not need to access or know about them Access specifiers control a client’s access to individual data members and member functions PHP Programming with MySQL

607 Summary (continued) Serialization refers to the process of converting an object into a string that you can store for reuse A constructor function is a special function that is called automatically when an object from a class is instantiated A destructor function cleans up any resources allocated to an object after the object is destroyed PHP Programming with MySQL

608 Summary (continued) Accessor functions are public member functions that a client can call to retrieve the value of a data member Mutator functions are public member functions that a client can call to modify the value of a data member PHP Programming with MySQL

609 Summary (continued) When you serialize an object with the serialize() function, PHP looks in the object’s class for a special function named __sleep(), which you can use to perform many of the same tasks as a destructor function When the unserialize() function executes, PHP looks in the object’s class for a special function named __wakeup(), which you can use to perform many of the same tasks as a constructor function PHP Programming with MySQL


Download ppt "Chapter 1 Getting Started with PHP PHP Programming with MySQL"

Similar presentations


Ads by Google