8. Control-Flow and Arrays

What We Will Cover


Elucidations

Homework Questions?

Quiz Questions?

Questions from last class?

  • Comments on using the suggested organization for your project?
  • Any problems zipping files?
  • Problems using dbconvars.php
  • Printing double quotes inside of double quotes
    • Use escape characters for HTML
    • Use single quotes around strings in SQL
  • Use of DB wrappers
  • Use of $HTTP_POST_VARS vs. $_POST
    • $HTTP_POST_VARS is deprecated
  • Using mysql_error() to debug database connections

8.1: Relationships, Truth and Conditions

Objectives

At the end of the lesson the student will be able to:

  • Use conditional statements to compare numerical and string data values

8.1.1: Relationship Values and Truth

  • In addition to arithmetical operations, all computers can compare numbers
  • Many decisions can be reduced to choosing between two numbers
  • Comparing numbers can make computers seem "intelligent"
  • Expressions that compare operands are called relational expressions
    • Also called conditions
  • Simple relational expressions have one relational operator comparing two values
  • relational expression

  • A relational expression always evaluates to either true or false
  • The relational operators are:
  • Math Name PHP Example Result
    = Equal to == or
    ===
    5 == 10
    2 == 2
    false
    true
    Not equal to != or
    !==
    5 != 10
    2 != 2
    true
    false
    < Less than < 5 < 10
    5 < 5
    5 < 2
    true
    false
    false
    Less than or equal to <= 5 <= 10
    5 <= 5
    5 <= 2
    true
    true
    false
    > Greater than > 5 > 10
    5 > 5
    5 > 2
    false
    false
    true
    Greater than or equal to >= 5 >= 10
    5 >= 5
    5 >= 2
    false
    true
    true

  • Operators === and !== include data types in the comparison

What is Truth?

  • "What is truth?" may seem more appropriate for philosophy than programming
  • However, in programming we have to know how the computer interprets truth
  • PHP interprets the following as false and every other value as true:
    • boolean FALSE
    • integer 0 (zero)
    • float 0.0 (zero)
    • empty strings "", and the string "0"
    • arrays with zero elements (not covered yet)
    • objects with zero elements (not covered yet)
    • special type NULL (such as variables not assigned a value)
  • Note that a NULL character (\0) does not display anything in a browser
  • To view information about variables, you can use var_dump()
  • Thus, to see the truth of a relational expression, you can use something like:
  • var_dump(5 == 10);

Further Information

8.1.2: Using the if Statement

  • Use an if statement to make a choice
  • Executes a section of code only if a test condition is true
  • The code to execute is put between a pair of curly brackets
  • If the test condition is false, the computer skips the code
  • if (condition) {
       // execute statements only if true
    }
    
  • The test condition can be any expression that evaluates to true or false
  • For clarity, write the if on a different line than the statements to execute
  • Also, you should indent the statements to execute

For Example

  • Consider a simple guessing game application.
  • We use a simple form to collect a guess from the user
  • Save the form in our /home/cis165/public_html directory as guessform.html
  • <html>
    <head>
    <title>Guessing Game!</title>
    </head>
    
    <body>
    <form method="get" action="guess.php">
    
    <p>I'm thinking of a number between 1 and 10.<p>
    <p>Can you guess it?</p>
    <input type="text" name="guess" size="20"></p>
    
    <input type=submit name="submit" value="Submit">
    <input type=reset value="Reset">
    </form>
    
    </body>
    </html>
    
  • Report the success using the following code
  • Save the code as guess.php
  • <html>
    <head>
    <title>Guessing Game Response</title>
    </head>
    <body>
    <?php
    if ($_REQUEST["guess"] == 7) {
        echo 
    "<p>*** Correct! ***</p>\n";
    }
    ?>
    </body>
    </html>

  • What is displayed if the user enters 7?
  • What is displayed if the user enters 5?

Further Information

8.1.3: Using the if-else Statement

  • Sometimes we want to choose one action or another
  • If a condition is true
    • then do this
  • Otherwise it is false
    • so do something else
  • General syntax:
  • if (condition == true) {
        // execute statements only if true
    } else {
        // execute statements only if false
    }
    
  • Note that there is no condition for the else clause
  • For clarity, if and else are written on different lines than the statements
  • Also, the statements are indented

For Example

  • We rewrite our previous example to use an if-else statement
  • if ($_REQUEST["guess"] == 7) {
        echo "<p>*** Correct! ***</p>\n";
    } else {
        echo "<p>Sorry, that is not correct.</p>\n";
    }
    

Further Information

8.1.4: Using the elseif Statement

  • Use an elseif clause when you have a list of values to consider
    • Same as an if statement followed by an else
  • Allows you to specify additional test conditions
  • Only executes when previous conditions are false
  • if (condition1 == true) {
        // execute statements only if condition1 is true
    } elseif (condition2 == true) {
        // execute statements only if condition2 is true
        // and condition1 is false
    } else {
        // execute statements if nothing preceding is true
    }
    
  • Tests multiple conditions until the first true condition is found
  • If a true condition is found, executes code within the block
  • Then the computer skips the remainder of the if-elseif-else chain
  • You can end with an else clause for when no conditions are true

For Example

  • We rewrite our previous example to use an if-elseif-else structure
  • if ($_REQUEST["guess"] == 7) {
        echo "<p>*** Correct! ***</p>\n";
    } elseif ($_REQUEST["guess"] < 7) {
        echo "<p>Sorry, that is too low.</p>\n";
    } else {
        echo "<p>Sorry, that is too high.</p>\n";
    }
    
  • Note the arrangement of elseif statements
  • What is displayed if the user enters 5? Why?
  • What is displayed if the user enters 9? Why?

Further Information

8.1.5: Using Logical Operators

  • Sometimes you want to consider several relational expressions at once
  • For this we can use logical operators
  • Use ! (NOT) operator to reverse value of expression
  • Use and to AND two or more conditions
    • Also, you can spell AND as: &&
  • Use or to OR two or more conditions
    • Also, you can spell OR as: ||

    ! Operator
    If expr is... Then ! expr is... Example Result
    true false !true false
    false true !(5 < 2) true

  • and operator returns true only if expressions on both sides are true
  • and (&&) Operator
    If expr1 is... And expr2 is... Then expr1 and expr2 is... Example Result
    true true true 5 < 10 and 5 > 2 true
    true false false 5 < 10 and 5 < 2 false
    false true false 5 > 10 and 5 > 2 false
    false false false 5 > 10 and 5 < 2 false

  • or operator returns true if either expression is true
  • or (||) Operator
    If expr1 is... || expr2 is... Then expr1 or expr2 is... Example Result
    true true true 5 < 10 or 5 > 2 true
    true false true 5 < 10 or 5 < 2 true
    false true true 5 > 10 or 5 > 2 true
    false false false 5 > 10 or 5 < 2 false

For Example

  • We want to verify that users enter correct values
    • Such as a number between 1 and 10
  • You can use a logical or to check the value of two fields at once
  • if ($num < 1 or $num > 10) {
      print "Error: enter a number between 1 and 10";
    }
    
  • An alternate way of checking uses the NOT operator with the AND operator
  • if (!($num >= 1 and $num <= 10)) {
      print "Error: enter a number between 1 and 10";
    }
    
  • Tip: construct a truth table to verify your logic

Check Yourself

  • What is displayed by running the following code?
  • $bb = true;
    if ($bb or !$bb) {
        echo "That is the question!";
    }
    

Further Information

8.1.6: Comparing Strings

  • PHP represents strings using the ASCII code values
    • Acronym for American Standard Code for Information Interchange
    • Pronounced (“ask-ee”)
  • ASCII provides a standard, numerical way to represent characters
  • Every letter, number, and symbol is translated into a code number
  • Digits are stored in order from '0' to '9'
    • Digit '0' is code value 48
    • Digit '1' is code value 49
    • And so on to '9', which is code value 57
  • Uppercase letters of the alphabet are stored in order from 'A' to 'Z'
    • Letter 'A' is code value 65
    • Letter 'B' is code value 66
    • Up to 'Z' which is code value 90
  • Similarly, lowercase letters are stored in order from 'a' to 'z'
    • Letter 'a' is code value 97
    • Letter 'b' is code value 98
    • Up to 'z' which is code value 122
  • Also, a space is code value 32, which is less than all letters and digits

Comparing Codes

  • Notice that digits come before uppercase letters
  • Also, uppercase letters come before lowercase letters
  • Since all letters and digits are numbers, you can compare strings just like numbers
  • PHP lets you use all the relational operators to compare string values:
    ==, !=, <, >, <= and >=
  • These operators produce results like you would expect when comparing words alphabetically

For Example

  • As an example, let us compare two names
  • Following PHP segment compares "Edward" and "Joan"
  • $name1 = "Edward";
    $name2 = "Joan";
    if ($name1 == $name2) {
        print "$name1 is equal to $name2";
    }
    if ($name1 != $name2) {
        print "$name1 is not equal to $name2";
    }
    

Further Information

8.1.7: Summary

  • Many decisions can be reduced to choosing between two numbers
  • Comparing numbers can make computers seem "intelligent"
  • To compare numbers, you use relational operators
  • Relational operators include:
  • ==  !=  <   <=  >   >= === <== >==
    
  • Similarly, you can compare letters since letters are stored as numbers
  • Relational expressions always evaluate to either true or false
  • To make choices in your scripts, use one of the following:
  • if
    if-else
    if elseif elseif ... else
    
  • When you need to compare several conditions, you use logical operators
  • !   and   or
  • For example:
  • if (($num < 1) or ($num > 10) {
      print "Error: enter a number between 1 and 10";
    }
    

Exercise 8.1

In this exercise we explore using relational and logical operators with if-elsif-else statements.

  1. Start a text file named exercise8.txt.
  2. Prepare the exercise header as described in the HowTo on submitting exercises
  3. Label this exercise: Exercise 8.1
  4. Submit all exercises for today's lesson in one file unless instructed otherwise
  5. Complete the following exercises and answer any questions.

Specifications

A student's letter grade is calculated according to the following table:

Numerical Grade Letter Grade
greater than or equal to 90 A
less than 90 but greater than or equal to 80 B
less than 80 but greater than or equal to 70 C
less than 70 but greater than or equal to 60 D
less than 60 F

  1. Write a program that accepts a students numerical grade, converts the grade to an equivalent letter grade, and displays the letter grade.
  2. Q1: What relational operators should you use?

    Q2: What statements should you use to make sure that the correct grade is given for any score?

    Q3: Do you need to use logical operators? Why or why not?

  3. Submit your program along with your exercise8.txt file.

You can use the following code to get started.

grade.html

<html>
<head>
<title>Score Entry</title>
</head>

<body>
<form method="get" action="grade.php">

<p>What was your score?
<input type="text" name="score" size="10"></p>

<input type=submit name="submit">
<input type=reset value="Reset"></tr>
</form>

</body>
</html>

grade.php

<html>
<head><title>Grade Report</title></head>
<body>
<?php
$score 
trim($_REQUEST["score"]);
print 
"The score was $score, which is an ";
// Enter code here

?>
</body>
</html>

8.2: Using Loops to Repeat statements

Objectives

At the end of the lesson the student will be able to:

  • Use while and for statements to repeat sections of code
  • Apply commonly-used looping patterns
  • Avoid common looping problems

8.2.1: Introduction to Loops

  • Loops are used to repeat sections of code
  • PHP has 3 general-purpose looping statements
  • while
    do-while
    for
    
  • You can use any of these looping statement and achieve the same result
  • Thus, I am only going to cover while and for statements
  • General structure for all loops:
    • Initialization code
    • Loop condition -- evaluated during the loop
    • Loop body

8.2.2: Using the while Loop

  • Use a while loop to repeat a section of code
  • Repetition continues as long as the loop test condition remains true
  • while loop Syntax:
  • //Initialization
    ...
    while (condition) { //loop condition
       //loop body
       ...
    }
    
  • Initialization statements usually precede the while loop
  • The condition is like that used for an if-statement
  • A while loop checks the condition at start of every loop iteration
    • Continues as long as the condition evaluates to true
  • Note that if the loop condition is initially false then the loop body never executes
  • A loop body can be a single statement or a block

Further Information

8.2.3: Looping Examples

  • Let us look at some ways to use loops

Counter-Controlled Loops

  • Use loops this way when you know how many times to repeat a section of code
  • The key is a variable called the counter
    1. Initialize the counter variable to 0
    2. Set the loop condition to check for the maximum count
    3. Adjust the counter variable inside the body of the loop
  • For example:
  • <?php
      
    //Initialization
      
    $count 0;
      echo 
    "Before loop: count = $count" ;
      while (
    $count 5) { //loop condition
          //loop body
          
    $count $count 1;
          echo 
    "<br>count = $count\n";
      }
      echo 
    "<br>After loop: count = $count" ;
    ?>

  • A variation is to start at the maximum value and count down

Sentinel-Controlled Loops

  • Use a sentinel when you can use input data to tell the program when to stop
  • Looping continues as long as the data value read is not a sentinel value
  • When a sentinel value is read, the loop exits
  • Commonly used for reading input from a user or file
  • Following example uses a loop to extract a file name from a URL
  • To trace the execution, we keep track of the variables used in the loop body
  • <?php
      $url 
    " http://www.edparrish.com/path/file.php";

      
    //Loop initialization
      
    $count 0;
      
    $letter "";
      
    $filename "";
      while (
    $letter != "/") {
        
    //loop body
        
    $filename $letter $filename;
        
    $count $count 1;
        
    $letter substr($url, -$count1);
      }
      print 
    "Filename: $filename";
    ?>

  • $letter is the sentinel variable
  • Sentinel value is a slash (/)
  • Starts counting from the end of the $url string
  • Loop ends when a slash is found

8.2.4: Loopy Errors

Infinite Loops

  • Common error: unintentional infinite loop
  • For example, what is wrong with the following code?
  • <html>
    <head><title>Loopy One</title></head>
    <body>
    <?php
    $count 
    0;
    while (
    $count 5); {
        echo 
    "$count ";
    }
    ?>
    </body>
    </html>

  • What do we see when we run it?
  • Fatal error: Maximum execution time of 30 seconds exceeded...
    

Empty Statements

  • Remember that statements are terminated by a semicolon
  • Is the following a legal statement?
  • ;
  • Known as an empty or null statement
  • Empty statements are a common source of infinite loops
  • For example, what is wrong with the following code?
  • <html>
    <head><title>Loopy Two</title></head>
    <body>
    <?php
    $count 
    0;
    while (
    $count 5); {
        echo 
    "$count ";
        
    $count++;
    }
    ?>
    </body>
    </html>

Off-By-One Errors

  • A common looping problem is the off-by-one error
  • Often a less-than is confused with a less-than-or-equal-to
  • For example, to sum the numbers from 1 to 5, including both endpoints, what is wrong with:
  • <html>
    <head><title>Loopy Three</title></head>
    <body>
    <?php
    $sum 
    0;
    $count 0;
    echo 
    "Initial sum = $sum\n";
    while (
    $count 5) {
        
    $sum $sum $count;
        echo 
    "<br>After adding $count, sum = $sum\n";
        
    $count++;
    }
    echo 
    "<br>Total sum = $sum"
    ?>
    </body>
    </html>

Tracing Variables

  • One good way to discover loop errors is to trace key variables
  • Tracing variables means watching them change as the program executes
  • You can insert temporary output statements in your program
  • For instance, we had trace statements in the infinite loop examples above
  • What variables would we trace for the off-by-one error example?

8.2.5: Using the for Loop

  • The for loop provides a compact alternative to the while loop
  • Mostly used for counter-controlled loops
  • Syntax:
  • for (initialization; condition; increment) {
       //loop body
       ...
    }
    
  • Initialization, loop-test, and increment expressions are part of the syntax
  • initializer expression: defines the initial value used to control the loop
  • condition expression: determines when the loop will end
  • increment expression: evaluated at the end of each loop iteration
  • Statements to repeat are enclosed in curly brackets
  • For example:
  • for ($i = 0; $i < $max; $i = $i + 1) {
        echo "Count = $i ";
    }
    
  • Execution sequence is as follows:
  1. When for statement reached -- initialization executes
  2. If the condition evaluates to true:
    1. Execute statements in the body of the loop
    2. When the end of loop body is reached, execute the increment expression
    3. Return to step 2
  3. Loop is finished: continue with statements after the loop

Counter-Controlled-Loop Example

  • What is displayed by the following code?
  • <?php
        $max 
    5;
        for (
    $i 0$i $max$i $i 1) {
            echo 
    "i = $i <br>";
        }
        echo 
    "After loop i = $i" ;
    ?>

  • Note that code is indented in the loop body for readability

Further Information

8.2.6: Nesting Loops

  • Often necessary to have one loop inside another
  • Important to use indentation to show the relationship between the loops
  • Following example shows this structure
  • Let's follow the execution sequence before checking the result
  • <?php
    for ($outer 1$outer 4$outer++) {
       echo 
    "<p>outer = $outer<br>";
       for (
    $inner 1$inner 4$inner++) {
          echo 
    "..inner = $inner<br>";
       }
    }
    ?>

8.2.7: Summary

  • Loops are used to repeat sections of code
  • General loop structure:
    • Initialization code
    • Loop condition -- evaluated during the loop
    • Loop body
  • The while loop is the most basic repetition statement
  • A more compact repetition statement is the for loop
  • for (initialization; condition; increment) {
       //loop body
    }
    
  • Several common applications a loop
    • Counter-controlled loops
    • Sentinel-controlled loops
  • Several problems that can occur when using a loop
    • infinite loops: loops that "never" stop
    • Off-by-one errors: start or stop at a wrong value
  • Tracing variables is a good way to discover loop errors
  • It is legal code to have one loop nested inside another

Exercise 8.2

With your partner, complete the following:

  1. Label this exercise: Exercise 8.2
  2. Both for loops and while loops can perform the same tasks. To demonstrate this, convert the following for loop into a while loop.
  3. <?php
        $max 
    5;
        for (
    $i 0$i $max$i $i 1) {
            echo 
    "i = $i <br>";
        }
        echo 
    "After loop i = $i" ;
    ?>

  4. Save the completed code in your exercise8.txt file.

8.3: Using Arrays

Objectives

At the end of the lesson the student will be able to:

  • Write code to initialize arrays
  • Access array elements
  • Sometimes useful to group related data values into a list
  • Can use a variable type called an array to store data in a list
  • Then able to operate on the array data as a group

8.3.1: About Arrays

Array: a single name for a collection of data values

  • Arrays are a type of data structure
  • -- a way to organize data
  • An array is used to process a collection of data as a group
    • Scores
    • Temperatures
  • Why do we need arrays?
  • Imagine keeping track of 5 test scores, or 100, or 1000 in memory
    • How would you name all the variables?
    • How would you process each of the variables?
  • Arrays provide a convenient solution to these problems
  • Entire array referred to by a single identifier
  • Each element uniquely identified by an index

For Example

  • One-dimensional array is like single row of data in spreadsheet or table
  • $score[0] $score[1] $score[2] $score[3] $score[4]
    90 95 87 89 98

  • Top row shows the indices for an array named "$score"
  • Individual items are referenced by the index (a.k.a. subscript)
  • PHP uses a type of array known as an associative array
    • Individual elements can be accessed by a name rather than a number
  • Note that array indexes start at 0 by default

8.3.2: Creating Arrays

  • Like other PHP variables, arrays do not need to be declared in advance
  • Just type the variable name followed by square brackets
  • You can assign a value to a single array element
  • $myArray[] = "someValue";
  • After assignment, you can use array element like any other variable
  • print $myArray[0];
  • By default, arrays indexes start at zero (0)

For Example:

  • What will be displayed by running the following code?
  • <?php
    // Initializing values
    $myArray[] = "zero";
    $myArray[] = "one";
    $myArray[] = "two";

    // Accessing values
    echo "$myArray[0], $myArray[1], $myArray[2]";
    ?>

Using the Array Function

  • An array function uses more compact code to initialize arrays
  • <?php
    // Initializing values
    $myArray = array("zero""one""two");

    // Accessing values
    echo "$myArray[0], $myArray[1], $myArray[2]";
    ?>

8.3.3: Selecting Array Items

  • Individual array elements are accessed using the array name and an index
  • Use the array operator [] to specify the index
  • Indexes should be an integer expression or a string
  • Arrays indexes can be literal values or a variable

<?php
$dayName 
= array("Sunday""Monday""Tuesday",
    
"Wednesday""Thursday""Friday""Saturday");

echo 
"$dayName[0]<br>$dayName[1]<br>$dayName[2]<br>";
echo 
"$dayName[3]<br>$dayName[4]<br>$dayName[5]<br>";
echo 
$dayName[6];
?>

  • If you wish, you can set index values for your array

<?php
$dayName 
= array(1=>"Sunday""Monday""Tuesday",
    
"Wednesday""Thursday""Friday""Saturday");

echo 
"$dayName[1]<br>$dayName[2]<br>$dayName[3]<br>";
echo 
"$dayName[4]<br>$dayName[5]<br>$dayName[6]<br>";
echo 
$dayName[7];
?>

  • Above example sets the first index to the number 1
  • Subsequent assignment of values use the maximum index + 1
  • If you try to access an index beyond those defined, PHP returns NULL

8.3.4: Using Loops with Arrays

  • Loops are often used as a way to iterate () through array items
  • For example, following code uses a loop to list each item in an array
  • Uses the count function to return the number of items in the array
  • <?php
    $dayName 
    = array("Sunday""Monday""Tuesday",
        
    "Wednesday""Thursday""Friday""Saturday");

    for (
    $i 0$i count($dayName); $i++) {
      echo 
    "$dayName[$i]<br>";
    }
    ?>

Using foreach

  • Another way to access each element is the foreach loop statement
  • Syntax:
  • foreach (array as variable) {
       //loop body
       ...
    }
    
  • Automatically assigns variable a subsequent item in each loop iteration
  • Note that foreach works only with arrays

Example Using foreach

  • Following displays the contents of the array named $dayName
  • <?php
    $dayName 
    = array("Sunday""Monday""Tuesday",
        
    "Wednesday""Thursday""Friday""Saturday");

    foreach (
    $dayName as $day) {
      echo 
    "$day<br>";
    }
    ?>

  • Note that each array item is accessed and displayed in order

8.3.5: Using Arrays for Multiple Form Values

  • Check boxes and selections lists can provide more than one value from a form
  • Can use an array to generate the items
    • Makes it easy to add more items to the list

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head><title>Languages</title></head>

<body>
<h3>Make your vote</h3>
<form action="langscript.php" method="post">
<p>Preferences:
<?php
$prefs 
= array("ASP","JSP","PHP","Other");
foreach (
$prefs as $item) {
  print 
'<input type="checkbox" name="pref[]" value="';
  print 
$item.'"> '.$item;
}
?>
<p><input type="submit" value="Click to Vote!"></p>
</form>
</body>
</html>

  • Note the use of square brackets ([]) in the form name
    • Required to send multiple values to the script
  • You can then use an array to process the items

<html>
<head>
<title>Your Vote Counts!</title>
</head>

<body>
<h3>Your Vote Counts!</h3>
<?php

if (empty($_REQUEST['pref'])) {
  print 
"Oh no! Please vote!";
} else {
  print 
"<p>You voted for: <ul>";
  foreach (
$_REQUEST['pref'] as $item) {
     print(
"<li>$item</li>");
  }
  print 
"</ul>";
}
?>
</body>
</html>

  • Note the use of the empty function to test if a variable has a value assigned
  • if (empty($_REQUEST['pref']))
  • Another useful function for testing variables is isset
    • Tests to see if a variable exists or not
  • Also note that using square brackets in names may not validate as standard HTML on some validators
  • However, it seems to on the WDG HTML Validation Results

8.3.6: Associative Arrays

  • Arrays indices in PHP can be strings rather than numbers
    • Known as an associative array
  • The string value is used to look up the location of the data value

Creating Associative Arrays

  • The following code creates an associative array
  • $course['cis154'] = 'Parrish';
    $course['cis156'] = 'Griffith';
    $course['cis165'] = 'Parrish';
    
  • Also, you can create associative arrays with the array function
  • You must specify the index name followed by => and the value
  • For instance, we can create a cross-reference between month names and number of days in the month
  • $months = array('Jan'=>31, 'Feb'=>28, 'Mar'=>31,
      'Apr'=>30, 'May'=>31, 'Jun'=>30, 'Jul'=>31,
      'Aug'=>31, 'Sep'=>30, 'Oct'=>31, 'Nov'=>30,
      'Dec'=>31);
    
  • Then we can access an array element like this:
  • $days = $months['Nov'];
  • This is similar syntax to arrays we have used so far
  • The main difference is the use of string values within the square brackets
  • When used with the foreach statement, you can access both the index name and item name
  • foreach ($months as $name=>$days) {
      print "Index = $name and value = $days<br>";
    }
    
  • Also, you can change the value of any array item by assigning a new value
  • $course['cis156'] = 'Griffin';

For Example

    <?php
    $months 
    = array('Jan'=>31'Feb'=>28'Mar'=>31,
      
    'Apr'=>30'May'=>31'Jun'=>30'Jul'=>31,
      
    'Aug'=>31'Sep'=>30'Oct'=>31'Nov'=>30,
      
    'Dec'=>31);

    foreach (
    $months as $name=>$days) {
      print 
    "Index = $name and value = $days<br>";
    }
    ?>

8.3.7: Superglobal Arrays

  • PHP has a number of predefined variables available in any script
  • Some of these are associative arrays known as superglobals
  • Superglobal arrays provide a wealth of useful information for form processing
  • We looked at these briefly in lesson 7.2.8
  • For example, to use $_REQUEST:
  • $_REQUEST["submit"]
  • You can also specify the field name using a variable
  • $_REQUEST[$field]

Superglobal Arrays used with Forms

Array Description
$_GET Access to variables passed via the HTTP GET method.
$_POST Access to variables passed via the HTTP POST method.
$_REQUEST Access to variables passed via both the HTTP GET and POST methods.

Debugging Forms

  • One valuable technique for debugging forms is to use function var_dump()
  • For example, to view all the variable data sent from a browser use:
  • var_dump($_REQUEST);
    
  • Insert the above code near the top of your script that receives the form data
  • Then you will see all the variables sent from the form

8.3.8: Summary

  • Arrays are convenient ways to process a list of data
  • Like other PHP variables, arrays do not need to be declared in advance
  • Just type the variable name followed by square brackets
  • You can assign a value to a single array element
  • $myArray[] = "someValue";
  • After assignment, you can use array element like any other variable
  • echo $myArray[0];
  • An array function uses more compact code to initialize arrays
  • $myArray = array("zero", "one", "two");
  • Loops are often used as a way to iterate through array items
  • PHP has a special type of loop for use with arrays: foreach
  • You can declare arrays in a form for processing in you PHP scripts
  • Place square brackets '[]' after the element name
  • Arrays indices in PHP can be strings rather than numbers
  • Allows cross-referencing, among other uses:
  • $months = array('Jan'=>31, 'Feb'=>28, 'Mar'=>31,
      'Apr'=>30, 'May'=>31, 'Jun'=>30, 'Jul'=>31,
      'Aug'=>31, 'Sep'=>30, 'Oct'=>31, 'Nov'=>30,
      'Dec'=>31);
    
  • Superglobal arrays provide another way to access form variables
  • $_REQUEST[$field]
  • You can use var_dump() with $_REQUEST to view all form variables
  • var_dump($_REQUEST);
    

Exercise 8.3

Instructions:

Use the next 10 minutes to complete the following.

  1. Label this exercise: Exercise 8.3
  2. Modify the two PHP scripts below to add two more checkboxes with your choice of labels.
  3. Submit the modified files with the exercises for today's lesson.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head><title>Languages</title></head>

<body>
<h3>Make your vote</h3>
<form action="langscript.php" method="post">
<p>Preferences:
<?php
$prefs 
= array("ASP","JSP","PHP","Other");
foreach (
$prefs as $item) {
  print 
'<input type="checkbox" name="pref[]" value="';
  print 
$item.'"> '.$item;
}
?>
<p><input type="submit" value="Click to Vote!"></p>
</form>
</body>
</html>

<html>
<head>
<title>Your Vote Counts!</title>
</head>

<body>
<h3>Your Vote Counts!</h3>
<?php

if (empty($_REQUEST['pref'])) {
  print 
"Oh no! Please vote!";
} else {
  print 
"<p>You voted for: <ul>";
  foreach (
$_REQUEST['pref'] as $item) {
     print(
"<li>$item</li>");
  }
  print 
"</ul>";
}
?>
</body>
</html>

8.4: Arrays, Tables and Meta-data

Objectives

At the end of the lesson the student will be able to:

  • Fetch data from MySQL in arrays
  • Create HTML tables
  • Display MySQL data in HTML tables
  • Use result set metadata

8.4.1: Fetching Arrays from MySQL

  • PHP provides mysql_fetch_array() to read MySQL data into arrays
  • $row = mysql_fetch_array($result, MYSQL_BOTH);
  • Similar functions are:
  • All of these usually provide better performance than mysql_result()
  • You can use mysql_num_rows() to count the number of rows in query results
  • $numRows = mysql_num_rows($result);
  • Also, you can use mysql_num_fields() to count the number of fields in query results
  • $numRows = mysql_num_fields($result);
  • With loops, you can use these functions to make a query and display the results

For Example

  • Let us create a PHP script by copying the following code into a text editor
  • Then we save the file in /home/cis165/public_html directory as datafetch.php

<?
require_once("includes/dbconvars.php");

// Open the connection
$dbCnx mysql_connect($dbhost$dbuser$dbpwd)
    or die(
"Could not connect: ".mysql_error());
mysql_select_db($dbname$dbCnx)
    or die(
"Could not select db: ".mysql_error());

// Make the query
$sql "SELECT * FROM products";
$result mysql_query($sql)
    or die(
"Query failed: ".mysql_error());

// Count number of rows returned
$numRows mysql_num_rows($result);
echo 
"<p>Number of rows: $numRows</p>\n";

// Outer loop copies each row into $row
while ($row mysql_fetch_assoc($result)) {
    
// Inner loop displays each column of $row
    
echo "<p>";
    foreach (
$row as $item) {
        echo 
"$item ";
    }
    echo 
"</p>\n";
}

// Clean up
mysql_free_result($result);
mysql_close($dbCnx);
?>

  • Note use of the or die construct during connections and queries
    • Allows making up your own error message when a problem occurs
  • Also can use the "@" prefix to silence default error messages
  • Note that the outer loop copies each row of data into $row
  • Is $row an array?
  • Inner loop displays each column of information
  • What do you think of the layout of the data?

8.4.2: Creating HTML Tables

  • You can use HTML tables to neatly format data in rows and columns
  • You define a table with the <table>...</table> tags
  • Put the tags where you want the table to appear in your HTML page
  • You can include a border attribute if you want a border displayed
  • You add rows to your table with the <tr>...</tr> tags
  • Thhen you use <td>...</td> to add the table data as cells or columns
  • Each row can have one or more table-data tags (columns)
  • <table border>
    <tr>
    <td>row 1, column 1</td>
    <td>row 1, column 2</td>
    </tr>
    <tr>
    <td>row 2, column 1</td>
    <td>row 2, column 2</td>
    </tr>
    </table>
    

    row 1, column 1 row 1, column 2
    row 2, column 1 row 2, column 2

Using Headings

  • Headings in a table are defined with the <th>...</th> tags
  • <table border>
    <tr>
    <th>Heading 1</th>
    <th>Heading 2</th>
    </tr>
    <tr>
    <td>row 1, column 1</td>
    <td>row 1, column 2</td>
    </tr>
    <tr>
    <td>row 2, column 1</td>
    <td>row 2, column 2</td>
    </tr>
    </table>
    

    Heading 1 Heading 2
    row 1, column 1 row 1, column 2
    row 2, column 1 row 2, column 2

Handling Missing Data

  • Note that some browsers do not display well when a cell has no data
  • <table border>
    <tr>
    <td>row 1, column 1</td>
    <td>row 1, column 2</td>
    </tr>
    <tr>
    <td></td>
    <td>row 2, column 2</td>
    </tr>
    </table>
    

    row 1, column 1 row 1, column 2
    row 2, column 2

  • You can avoid this by displaying a non-breaking space (&nbsp;) in cells
  • <table border>
    <tr>
    <td>row 1, column 1</td>
    <td>row 1, column 2</td>
    </tr>
    <tr>
    <td>&nbsp;</td>
    <td>row 2, column 2</td>
    </tr>
    </table>
    

    row 1, column 1 row 1, column 2
      row 2, column 2

Further Information

8.4.3: Displaying MySQL Data in Tables

  • You can use HTML tables to neatly format MySQL data
  • Using our previous example, we add table tags in the correct locations

For Example

<?
require_once("includes/dbconvars.php");

// Open the connection
$dbCnx mysql_connect($dbhost$dbuser$dbpwd)
    or die(
"Could not connect: ".mysql_error());
mysql_select_db($dbname$dbCnx)
    or die(
"Could not select db: ".mysql_error());

// Make the query
$sql "SELECT * FROM products";
$result mysql_query($sql)
    or die(
"Query failed: ".mysql_error());

// Count number of rows returned
$numRows mysql_num_rows($result);
print 
"<p>Number of rows: $numRows</p>\n";

// Show the results in a table
print "<table border=\"1\">\n";
while (
$row mysql_fetch_assoc($result)) {
    echo 
"<tr>\n";
    foreach (
$row as $item) {
        echo 
"<td>&nbsp;$item</td>\n";
    }
    echo 
"</tr>\n";
}
print 
"</table>\n";

// Clean up
mysql_free_result($result);
mysql_close($dbCnx);
?>

8.4.4: Adding Column Names with Meta-data

  • One thing missing from the table is names for the columns
  • You could add this information by hand
  • However, a better way is to use MySQLs meta-data
  • Meta-data: data about data.

  • MySQL keeps data about its databases, table structure and records
  • For example: database names, table names, column names, column types, etc.
  • When you make a query, the result set contains information about the data
  • This information is known as the result set metadata
  • PHP provides a number of functions to access the result set metadata
  • One method is the mysql_field_name()
    • Returns the name of the specified column (field)
    for ($i = 0; $i < $count; $i++) {
        print "<th>".mysql_field_name($result, $i)."</th>\n";
    }
    
  • Another method is the mysql_field_table
    • Returns the name of the specified table for a column (field)
    mysql_field_table($result, 0)
  • You can use this meta-data to provide table names and field names

<?
require_once("includes/dbconvars.php");

// Open the connection
$dbCnx mysql_connect($dbhost$dbuser$dbpwd)
    or die(
"Could not connect: ".mysql_error());
mysql_select_db($dbname$dbCnx)
    or die(
"Could not select db: ".mysql_error());

// Make the query
$sql "SELECT * FROM products";
$result mysql_query($sql$dbCnx)
    or die(
"Query failed: ".mysql_error());

// Show the table name
echo "<h4>Table: ";
echo 
mysql_field_table($result0);
echo 
"</h4>\n";

echo 
"<table border>\n";
// Show the column names as table headings
echo "<tr>\n";
$count mysql_num_fields($result);
for (
$i 0$i $count$i++) {
    echo 
"<th>&nbsp;";
    echo 
mysql_field_name($result$i);
    echo 
"</th>\n";
}
echo 
"</tr>\n";

// Show the result set data using HTML tables
while ($row mysql_fetch_assoc($result)) {
    echo 
"<tr>\n";
    foreach (
$row as $item) {
        echo 
"<td>&nbsp;$item</td>\n";
    }
    echo 
"</tr>\n";
}
echo 
"</table>\n";

// Clean up
mysql_free_result($result);
mysql_close($dbCnx);
?>

Further Information

Exercise 8.4

Instructions:

Use the next 10 minutes to complete the following.

  1. Label this exercise: Exercise 8.4
  2. Complete the following exercises and answer any questions.

Exercises and Questions

  1. Run the following example on your computer.
  2. Save the resulting HTML as sqltable.html
  3. Turn in the sqltable.html file along with the other exercises for this lesson.

<?
require_once("includes/dbconvars.php");

// Open the connection
$dbCnx mysql_connect($dbhost$dbuser$dbpwd)
    or die(
"Could not connect: ".mysql_error());
mysql_select_db($dbname$dbCnx)
    or die(
"Could not select db: ".mysql_error());

// Make the query
$sql "SELECT * FROM products";
$result mysql_query($sql$dbCnx)
    or die(
"Query failed: ".mysql_error());

// Show the table name
echo "<h4>Table: ";
echo 
mysql_field_table($result0);
echo 
"</h4>\n";

echo 
"<table border>\n";
// Show the column names as table headings
echo "<tr>\n";
$count mysql_num_fields($result);
for (
$i 0$i $count$i++) {
    echo 
"<th>&nbsp;";
    echo 
mysql_field_name($result$i);
    echo 
"</th>\n";
}
echo 
"</tr>\n";

// Show the result set data using HTML tables
while ($row mysql_fetch_assoc($result)) {
    echo 
"<tr>\n";
    foreach (
$row as $item) {
        echo 
"<td>&nbsp;$item</td>\n";
    }
    echo 
"</tr>\n";
}
echo 
"</table>\n";

// Clean up
mysql_free_result($result);
mysql_close($dbCnx);
?>

Wrap Up

Home | WebCT | Announcements | Course info | Expectations | Schedule
Project | Help | FAQ's | HowTo's | Links

Last Updated: April 02 2006 @12:03:20