Index
    Preface
      What This Book Is About
      What You Need to Know
      How This Book Is Organized
      How to Use This Book
      Conventions Used in This Book
      Using Code Examples
      How to Contact Us
      Web Site and Code Examples
      Acknowledgments
      Chapter 1.  Database Applications and the Web
      Section 1.1.  The Web
      Section 1.2.  Three-Tier Architectures
      Chapter 2.  The PHP Scripting Language
      Section 2.1.  Introducing PHP
      Section 2.2.  Conditions and Branches
      Section 2.3.  Loops
      Section 2.4.  Functions
      Section 2.5.  Working with Types
      Section 2.6.  User-Defined Functions
      Section 2.7.  A Working Example
      Chapter 3.  Arrays, Strings, and Advanced Data Manipulation in PHP
      Section 3.1.  Arrays
      Section 3.2.  Strings
      Section 3.3.  Regular Expressions
      Section 3.4.  Dates and Times
      Section 3.5.  Integers and Floats
      Chapter 4.  Introduction to Object-Oriented Programming with PHP 5
      Section 4.1.  Classes and Objects
      Section 4.2.  Inheritance
      Section 4.3.  Throwing and Catching Exceptions
      Chapter 5.  SQL and MySQL
      Section 5.1.  Database Basics
      Section 5.2.  MySQL Command Interpreter
      Section 5.3.  Managing Databases and Tables
      Section 5.4.  Inserting, Updating, and Deleting Data
      Section 5.5.  Querying with SQL SELECT
      Section 5.6.  Join Queries
      Section 5.7.  Case Study: Adding a New Wine
      Chapter 6.  Querying Web Databases
      Section 6.1.  Querying a MySQL Database Using PHP
      Section 6.2.  Processing User Input
      Section 6.3.  MySQL Function Reference
      Chapter 7.  PEAR
      Section 7.1.  Overview
      Section 7.2.  Core Components
      Section 7.3.  Packages
      Chapter 8.  Writing to Web Databases
      Section 8.1.  Database Inserts, Updates, and Deletes
      Section 8.2.  Issues in Writing Data to Databases
      Chapter 9.  Validation with PHP and JavaScript
      Section 9.1.  Validation and Error Reporting Principles
      Section 9.2.  Server-Side Validation with PHP
      Section 9.3.  JavaScript and Client-Side Validation
      Chapter 10.  Sessions
      Section 10.1.  Introducing Session Management
      Section 10.2.  PHP Session Management
      Section 10.3.  Case Study: Using Sessions in Validation
      Section 10.4.  When to Use Sessions
      Section 10.5.  PHP Session API and Configuration
      Chapter 11.  Authentication and Security
      Section 11.1.  HTTP Authentication
      Section 11.2.  HTTP Authentication with PHP
      Section 11.3.  Form-Based Authentication
      Section 11.4.  Protecting Data on the Web
      Chapter 12.  Errors, Debugging, and Deployment
      Section 12.1.  Errors
      Section 12.2.  Common Programming Errors
      Section 12.3.  Custom Error Handlers
      Chapter 13.  Reporting
      Section 13.1.  Creating a Report
      Section 13.2.  Producing PDF
      Section 13.3.  PDF-PHP Reference
      Chapter 14.  Advanced Features of Object-Oriented Programming in PHP 5
      Section 14.1.  Working with Class Hierarchies
      Section 14.2.  Class Type Hints
      Section 14.3.  Abstract Classes and Interfaces
      Section 14.4.  Freight Calculator Example
      Chapter 15.  Advanced SQL
      Section 15.1.  Exploring with SHOW
      Section 15.2.  Advanced Querying
      Section 15.3.  Manipulating Data and Databases
      Section 15.4.  Functions
      Section 15.5.  Automating Querying
      Section 15.6.  Table Types
      Section 15.7.  Backup and Recovery
      Section 15.8.  Managing Users and Privileges
      Section 15.9.  Tuning MySQL
      Chapter 16.  Hugh and Dave's Online Wines:A Case Study
      Section 16.1.  Functional and System Requirements
      Section 16.2.  Application Overview
      Section 16.3.  Common Components
      Chapter 17.  Managing Customers
      Section 17.1.  Code Overview
      Section 17.2.  Customer Validation
      Section 17.3.  The Customer Form
      Chapter 18.  The Shopping Cart
      Section 18.1.  Code Overview
      Section 18.2.  The Winestore Home Page
      Section 18.3.  The Shopping Cart Implementation
      Chapter 19.  Ordering and Shipping at the Online Winestore
      Section 19.1.  Code Overview
      Section 19.2.  Credit Card and Shipping Instructions
      Section 19.3.  Finalizing Orders
      Section 19.4.  HTML and Email Receipts
      Chapter 20.  Searching and Authentication in the Online Winestore
      Section 20.1.  Code Overview
      Section 20.2.  Searching and Browsing
      Section 20.3.  Authentication
      Appendix A.  Linux Installation Guide
      Section A.1.  Finding Out What's Installed
      Section A.2.  Installation Overview
      Section A.3.  Installing MySQL
      Section A.4.  Installing Apache
      Section A.5.  Installing PHP
      Section A.6.  What's Needed for This Book
      Appendix B.  Microsoft Windows Installation Guide
      Section B.1.  Installation Overview
      Section B.2.  Installing with EasyPHP
      Section B.3.  What's Needed for This Book
      Appendix C.  Mac OS X Installation Guide
      Section C.1.  Getting Started
      Section C.2.  Installing MySQL
      Section C.3.  Setting Up Apache and PHP
      Section C.4.  What's Needed for This Book
      Appendix D.  Web Protocols
      Section D.1.  Network Basics
      Section D.2.  Hypertext Transfer Protocol
      Appendix E.  Modeling and Designing Relational Databases
      Section E.1.  The Relational Model
      Section E.2.  Entity-Relationship Modeling
      Appendix F.  Managing Sessions in theDatabase Tier
      Section F.1.  Using a Database to Keep State
      Section F.2.  PHP Session Management
      Section F.3.  MySQL Session Store
      Appendix G.  Resources
      Section G.1.  Client Tier Resources
      Section G.2.  Middle-Tier Resources
      Section G.3.  Database Tier Resources
      Section G.4.  Security and Cryptography Resources
      Appendix H.  The Improved MySQL Library
      Section H.1.  New Features
      Section H.2.  Getting Started
      Section H.3.  Using the New Features
    Colophon
    Copyright



 

Previous Section  < Day Day Up >  Next Section

2.2 Conditions and Branches

Conditionals add control to scripts and permit choices. Different statements are executed depending on whether expressions are true or false. There are two branching statements in PHP: if, with the optional else clause, and switch, usually with two or more case clauses.

2.2.1 if...else Statement

The if statement conditionally controls execution. The basic format of an if statement is to test whether a condition is true and, if so, to execute one or more statements.

The following if statement executes the print statement and outputs the string when the conditional expression, $var is greater than 5, is true:

if ($var > 5)

    print "The variable is greater than 5";

The expressions used in the examples in this section compare integers. They can be used to compare strings but usually not with the expected results. If strings need to be compared, use the PHP string library function strcmp( ). It's discussed in more detail in Chapter 3.


Multiple statements can be executed as a block by encapsulating the statements within braces. If the expression evaluates as true, the statements within the braces are executed. If the expression isn't true, none of the statements are executed. Consider an example in which three statements are executed if the condition is true:

if ($var > 5)

{

    print "The variable is greater than 5.";



    // So, now let's set it to 5

    $var = 5;

    print "In fact, now it is equal to 5.";

}

Without the braces, an if statement executes only the single, immediately following statement when the conditional expression evaluates to true.

The if statement can have an optional else clause to execute a statement or block of statements if the expression evaluates as false. Consider an example:

if ($var > 5)

    print "Variable greater than 5";

else

    print "Variable less than or equal to 5";

It's also common for the else clause to execute a block of statements in braces, as in this example:

if ($var < 5)

{

    print "Variable is less than 5";

    print "-----------------------";

} 

else

{

    print "Variable is equal to or larger than 5";

    print "-------------------------------------";

}

Consecutive conditional tests can lead to examples such as:

if ($var < 5)

    print "Value is very small";

else

    if ($var < 10)

        print "Value is small";

    else

        if ($var < 20)

            print "Value is normal";

        else

            if ($var < 30)

                print "Value is big";

            else

                print "Value is very big";

The indentation in the preceding example highlights the nested nature of the multiple tests. If consecutive, cascading tests are needed, the elseif statement can be used. The choice of which method to use is a matter of personal preference. This example has the same functionality as the previous example:

if ($var < 5)

    print "Value is very small";

elseif ($var < 10)

    print "Value is small";

elseif ($var < 20)

    print "Value is normal";

elseif ($var < 30)

    print "Value is big";

else

    print "Value is very big";

2.2.2 switch Statement

The switch statement can be used as an alternative to if to select an option from a list of choices. The following example executes different code for different integer values, or cases of the variable $menu. A case clause is provided for values 1, 2, 3, and 4, with a default: case provided for all other values:

switch ($menu)

{

    case 1:

        print "You picked one";

        break;

    case 2:

        print "You picked two";

        break;

    case 3:

        print "You picked three";

        break;

    case 4:

        print "You picked four";

        break;

    default:

        print "You picked another option";

}

This example can be implemented with if and elseif, but the switch method is usually more compact, readable, and easier to type. The use of break statements is important: they prevent execution of statements that follow in the switch statement and force execution to jump to the statement that follows the closing brace.

If break statements are omitted from a switch statement, you can get an unexpected result. For example, without the break statements, if the user chooses option 3, the script outputs:

 You picked three. You picked four. You picked another option

These results are often a source of difficult-to-detect bugs; however, by intentionally omitting the break statement, you can group cases together as shown in the following switch statement:

$score = "Distinction";



switch ($score)

{

    case "High Distinction":

    case "Distinction":

        print "Good student";

        break;



    case "Credit":

    case "Pass":

        print "Average student";

        break;



    default:

        print "Poor student";

}

While not mandatory, the default: case is useful when default processing is performed on all but selected special cases, or to handle unexpected values when expected values have corresponding cases.

2.2.3 Conditional Expressions

Now we'll look at what can go inside the parentheses of an if statement, and other control statements. The most common conditional comparison is to test the equality or inequality of two expressions. Equality is checked with the double-equal operator, == ; if the value on the left-hand side is equal to the value on the right-hand side, then the expression evaluates to true. The expression ($var == 3) in the following example evaluates to true:

$var = 3;



if ($var == 3)

    print "Equals 3";

Inequality is tested with the not-equals operator, != . Both evaluate to a Boolean result of true or false.

If the equality operator == and the assignment operator = are unfamiliar, beware: they are easy to inadvertently interchange. This is a very common bug and hard to detect.

The value of the conditional expression ($var = 1) evaluates as true, because the expression takes its value from the value on the right hand side of the assignment operator; in this case 1. Here is an example of a common mistake, which overwrites the original value of the variable and always prints the statement:

if ($var = 1) 

 print "Variable equals 1.";

The error of incorrectly replacing an assignment with == is a far less common mistake. However, it's also difficult to detect because an incorrectly written assignment of $var == 1; is quietly evaluated as true or false with no effect on $var.


Expressions can be combined with parentheses and with the Boolean operators && (and) and || (or). For example, the following expression returns true and prints the message if $var is equal to 3 or $var2 is equal to 7:

if (($var == 3) || ($var2 == 7))

    print "Equals 3 or 7";

The following expression returns true and prints the message if $var equals 2 and $var2 equals 6:

if (($var == 2) && ($var2 == 6))

    print "The variables are equal to 2 and 6";

Interestingly, if the first part of the expression ($var == 2) evaluates as false, PHP doesn't evaluate the second part of the expression ($var2 == 6), because the overall expression can never be true; both conditions must be true for an && (and) operation to be true. Similarly, in the previous example, if ($var == 3), then there's no need to check if ($var2 == 7).

This short-circuit evaluation property has implications for design; to speed code, write the expression most likely to evaluate as false as the left-most expression, and ensure that computationally expensive operations are as right-most as possible.

Never assume that expressions combined with the Boolean operators && and || are evaluated. PHP uses short-circuit evaluation when determining the result of a Boolean expression.


Conditional expressions can be negated with the Boolean not operator !. The following example shows how an expression that tests if $var is equal to 2 or 6 is negated:

if (($var == 2) || ($var == 6))

    print "The variable var is equal to 2 or 6";



if (!(($var == 2) || ($var == 6)))

    print "The variable var is not equal to 2 or 6";

Unlike the && and || operators, ! works on a single value as the following example highlights:

// Set a Boolean variable

$found = false;



// The following message is printed

if (!$found)

    print "Expression is true";

More complex expressions can be formed through combinations of the Boolean operators and the liberal use of parentheses. For example, the following expression evaluates as true and prints the message if one of the following is true: $var equals 6 and $var2 equals 7, or $var equals 4 and $var2 equals 1.

if ((($var == 6) && ($var2 == 7)) || (($var == 4) && ($var2 == 1)))

    print "Expression is true";

As in assignment expressions, parentheses ensure that evaluation occurs in the required order.

    Previous Section  < Day Day Up >  Next Section

    Strompreise zu teuer? Jetzt Stromvergleich erstellen.





    Copyright © 2010 | Domen maybe sale - bye this domen