ebook img

PHP 6/MySQL Programming for the Absolute Beginner PDF

512 Pages·2008·1.41 MB·English
Save to my drive
Quick download
Download
Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.

Preview PHP 6/MySQL Programming for the Absolute Beginner

156 PHP 6/MySQL Programming for the Absolute Beginner While it sounds complicated, an associative array (sometimes called a dictionary) is much like a normal array. While regular arrays rely on numeric indices, an associative array has a string index. Figure 5.5 shows a page created with two associative arrays. FIGURE 5.5 This page uses associative arrays to relate countries and states to their capital cities. Examining the assoc.php Program Imagine that you want to store a list of capital cities. You could certainly store the cities in an array. However, if your main interest is in the relationship between a state and its capital, it could be difficult to maintain the relationship using arrays. In this particular instance, it would be nice if you could use the name of the state as the array index (the element’s number, or position, within the array) rather than a number. Building an Associative Array Here is the code from assoc.php, which generates the array of state capitals: $stateCap["Alaska"] = "Juneau"; $stateCap["Indiana"] = "Indianapolis"; $stateCap["Michigan"] = "Lansing"; The associative array is just like a normal array, except the index values are strings. Note that the indices must be inside quotation marks. Once you have created an associative array, it is used much like a normal array. Chapter 5 • Better Arrays and String Handling 157 $cap = $stateCap["Alaska"]; print <<<HERE <h2>State Capital</h2> <dl> <dt>Alaska</dt> <dd>$cap</dd> </dl> HERE; Once again, the array’s index is a quoted string. The associative form is terrific for data like this. In essence, it lets you “look up” the capital city if you know the state name. In Dizzy-Array If all this associative array talk is making you dizzy, don’t panic. It’s just a new name for something you’re very familiar with. Think about the way HTML attributes work. Each tag has a number of attributes that you can use in any order. For example, a standard button might look like this: <input type = "button" value = "Save the world. "> This button has two attributes. Each attribute is made up of a name/value pair. The keywordstype and value are names (or indices, or keys, depending on how you want to think of it) and the terms button and Save the world. are the values associated with those names. Cascading style sheets (CSS) use a different syntax for exactly the same idea. The CSS element indicates a series of modifications to the paragraph tag: p (background-color:red; color:yellow; font-size:14pt) While the syntax is different, the same pattern applies. The critical part of a CSS def- inition is a list of name/value pairs. Associative arrays naturally pop up in one more place. As information comes into your program from an HTML form, it comes in as an associative array. The name of each 158 PHP 6/MySQL Programming for the Absolute Beginner element becomes an index, and the value of that form element is translated to the value of the array element. Later in this chapter you see how to take advantage of this. As associative array is simply a data structure used when the name/value relationship is the easiest way to work with some kind of data. Building an Associative Array with the array() Function If you know the values you want in your array, you can use the array() function to build an associative array. However, building associative arrays requires a slightly different syntax than the garden variety arrays you encountered in Chapter 4. I build the $worldCap array using the array() syntax: $worldCap = array( "Albania"=>"Tirana", "Japan"=>"Tokyo", "United States"=>"Washington DC" ); The array() function requires the data when you are building an ordinary array, but doesn’t require specified indices. The function automatically generates each element’s index by grab- bing the next available integer. In an associative array, you are responsible for providing both the data and the index. The general format for this assignment uses a special kind of assignment operator. The => operator indicates that an element holds some kind of value. I generally read it as holds, so you can say “Japan holds Tokyo”. In other words, "Japan" => "Tokyo" indicates that PHP should generate an array element with the index “Japan” and store the value “Tokyo” in that element. You can access the value of this array just like any other associative array: $cap = $worldCap["Japan"]; print <<<HERE <h2>World Capital</h2> <dl> <dt>Japan</dt> <dd>$cap</dd> </dl> HERE; Chapter 5 • Better Arrays and String Handling 159 Using foreach with Associative Arrays The foreach loop is just as useful with associative arrays as it is with vanilla arrays. However, it uses a slightly different syntax. Take a look at this code from the assoc.php page: foreach ($worldCap as $country => $capital){ print “$country: $capital<br>\n”;} // end foreach A foreach loop for a regular array uses only one variable because the index can be easily calculated. In an associative array, each element in the array has a unique index and value. The associative form of the foreach loop takes this into account by indicating two variables. The first variable holds the index. The second variable refers to the value associated with that index. Inside the loop, you can refer to the current index ($country) and value ($capital) using whatever variable names you designated in the foreach structure. Each time through the loop, you are given a name/value pair. In this example, the name is stored in the variable $country, because all the indices in this array are names of countries. Each time through the loop, $country has a different value. In each iteration, the value of the $capital variable contains the array value corresponding to the current value of $country. T R A P Unlike traditional arrays, you cannot rely on associative arrays to return in any particular order when you use a foreach loop to access array elements. If you need elements to show up in a particular order, call them explicitly. U B -I A A SING UILT N SSOCIATIVE RRAYS Associative arrays are extremely handy because they reflect a kind of information storage very frequently used. In fact, you’ve been using associative arrays in disguise ever since Chap- ter 2, “Using Variables and Input.” Whenever your PHP program receives data from a form, that data is actually stored in a number of associative arrays for you. The filter_input() function you’ve been using to extract information from web forms actually is extracting data from one of a number of associative arrays. When you worked with session variables in Chapter 4, you were also working with an asso- ciative array. Even when you use automated tools like filter_input(), it’s useful to know how to use the built-in arrays because: • Use of filter_input isn’t yet widespread; you’ll see lots of existing code that uses the associative array technique instead. • As of PHP6, you can’t use filter_input() for everything; for some types of input (like session variables) you still need to use associative arrays. 160 PHP 6/MySQL Programming for the Absolute Beginner • Occasionally you’ll find the built-in arrays easier to work with than the filter_input() technique. Introducing the formReader.php Program The formReader.php program is actually one of the first PHP programs I ever wrote, and it’s one I use frequently. It’s very handy, because it can take the input from any HTML form and report the names and values of each of the form elements on the page. To illustrate, Figure 5.6 shows a typical web page with a form. (This one is called sampleForm.html but the formReader program works with any form.) When the user clicks the Submit Query button, formReader responds with some basic diag- nostics, as you can see from Figure 5.7. Reading the $_REQUEST Array All the fields sent to your program are automatically stored in a special associative array called $_REQUEST. Each field name on the original form becomes a key, and the value of that field becomes the value associated with that key. If you have a form with a field called userName, you can get the value of the field by calling $_REQUEST[“userName”]. FIGURE 5.6 This form, which has three basic fields, calls the formReader.php program. Chapter 5 • Better Arrays and String Handling 161 FIGURE 5.7 The formReader.php program determines each field and its value. The $_REQUEST array is also useful because you can use a foreach loop to quickly determine the names and values of all form elements known to the program. The formReader.php pro- gram source code illustrates how this is done: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html lang="EN" dir="ltr" xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Form Reader</title> </head> <body> <h1>Form Reader</h1> <h3>Here are the fields I found on the form</h3> <?php print <<<HERE <table border = "1"> <tr> <th>Field</th> <th>Value</th> </tr> HERE; 162 PHP 6/MySQL Programming for the Absolute Beginner foreach ($_REQUEST as $field => $value){ print <<<HERE <tr> <td>$field</td> <td>$value</td> </tr> HERE; } // end foreach print "</table>\n"; ?> </body> </html> Note how I stepped through the $_REQUEST array. Each time through the foreach loop, the current field name is stored in the $field variable and the value of that field is stored in $value. TRICK I use this script when I’m debugging my programs. If I’m not getting the form elements I expected from a form, I put a foreach $_REQUEST loop in at the top of my program to make sure I know exactly what’s being sent to the program. Often this type of procedure can help you find misspellings or other bugs. PHP supplies a number of other extremely useful associative arrays. If you want to see a list of all the variables sent through the get mechanism, you can use $_GET. The $_POST array contains only those variables sent through a post request. The $_SESSION array contains all the session variables. In fact, the $_REQUEST array is simply the union of $_POST, $_GET, $_SESSION, and $_COOKIE. T I P It’s possible that you’ll see another variable shown on your form. If you’ve been experimenting with session variables, a sessionID variable may appear with a strange value. This is used to help the browser keep track of session variables. You can use the web developer toolbar (in Firefox) to clear session variables, or ignore them, as they will be automatically deleted when you close the browser. There are a few other special variables you might investigate in the PHP documentation for special situations. Chapter 5 • Better Arrays and String Handling 163 The $_SERVER variable contains information about the web server (especially $_SERVER [‘REMOTE_ADDR’]) that can be used to determine the IP address of the user. Finally, the $_FILES array contains a link to any files uploaded onto the server. These variables are called superglobals because they are automatically set as global variables and can be used anywhere in the program (even in functions) without any special global declaration. In the Real World The superglobals seem pretty great, and they are very popular tools. In fact, right now it is more common to use $_REQUEST to extract data from a form than to use the filter_input() technique described in the book. I recommend filter_input() because it uses the superglobals, but adds a layer of filtering to them. The default behavior of filter_input() makes the variables much more secure than they would be using straight $_REQUEST, and it gives you the ability to filter with much more detail, specifying that a particular input should only yield integer data, or should be pre- filtered to be an appropriate format for an e-mail address. See the extensive docu- mentation for filter_input() on the PHP documentation site. C M A REATING A ULTIDIMENSIONAL RRAY Arrays are very useful structures for storing various kinds of data into the computer’s mem- ory. Normal arrays are much like lists. Associative arrays are like name/value pairs. A third special type, a multidimensional array, acts much like table data. For instance, imagine you were trying to write a program to help users determine the distance between major cities. You might start on paper with a table like Table 5.1. TABLE 5.1 DISTANCES BETWEEN MAJOR CITIES Indianapolis New York Tokyo London Indianapolis 0 648 6476 4000 New York 648 0 6760 3470 Tokyo 6476 6760 0 5956 London 4000 3470 5956 0 164 PHP 6/MySQL Programming for the Absolute Beginner It’s reasonably common to work with this sort of tabular data in a computer program. PHP (and most languages) provides a special type of array to assist in working with this kind of information. The basicMultiArray program featured in Figures 5.8 and 5.9 illustrates how a program can encapsulate a table. FIGURE 5.8 The user can choose origin and destination cities from select groups. FIGURE 5.9 The program looks up the distance between the cities and returns an appropriate value.

Description:
If you are new to programming with PHP 6 and MySQL and are looking for a solid introduction, this is the book for you. Developed by computer science instructors, books in the for the absolute beginner™ series teach the principles of programming through simple game creation. You will acquire the sk
See more

The list of books you might like

Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.