Beginning PHP5, Apache, and MySQL Web Development split phần 2 ppsx

82 349 0
Beginning PHP5, Apache, and MySQL Web Development split phần 2 ppsx

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

How It Works When PHP comes across an include line in a script, it stops working on the current program and imme- diately shoots on over to whatever file it’s told to include. The server parses that second file and carries the results back to the original file, where the parsing continues from where it left off. Suppose you decided you didn’t really want the date to be shown with the leading zeros. Luckily, PHP has a solution for that when formatting the date function. Make the following change to your header.php file and see what happens: <div align=”center”><font size=”4”>Welcome to my movie review site!</font> <br> <?php echo “Today is “; echo date(“F j”); echo “, “; echo date(“Y”); ?> </div> Your problem is fixed, and it’s fixed in all the pages in your site, in one fell swoop. Using Functions for Efficient Code As with includes, functions make your code (and your typing) more efficient and easier to debug. Functions are blocks of code that can be called from anywhere in your program. They enable you to execute lines of code without having to retype them every time you want to use them. Functions can help set or update variables, and can be nested. You can also set a function to execute only if a certain criterion has been fulfilled. Functions are mini-programs within themselves. They don’t know about any other variables around them unless you let the other variables outside the function in through a door called “global.” You use the global $varname command to make an outside variable’s value accessible to the function. This does not apply to any values assigned to any variables that are global by default, such as $_POST, $_GET, and so on. Your function can be located anywhere within your script and can be called from anywhere within your script. Therefore, you can list all your commonly used functions at the top of your program, and they can all be kept together for easier debugging. Better yet, you can put all your functions in a file and include them in your programs. Now you’re rolling! PHP provides you with a comprehensive set of built-in functions (which you can find in Appendix C), but sometimes you need to create your own customized functions. 62 Chapter 2 06_579665 ch02.qxd 12/30/04 8:10 PM Page 62 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Try It Out Working with Functions This exercise demonstrates functions in action by adding a list of favorite movies to your movie reviews site. 1. Open your movie1.php page and modify it as shown in the highlighted text: <?php session_start(); $_SESSION[‘username’] = $_POST[‘user’]; $_SESSION[‘userpass’] = $_POST[‘pass’]; $_SESSION[‘authuser’] = 0; //Check username and password information if (($_SESSION[‘username’] == ‘Joe’) and ($_SESSION[‘userpass’] == ‘12345’)) { $_SESSION[‘authuser’] = 1; } else { echo “Sorry, but you don’t have permission to view this page, you loser!”; exit(); } ?> <html> <head> <title>Find my Favorite Movie!</title> </head> <body> <?php include “header.php”; ?> <?php $myfavmovie = urlencode(“Life of Brian”); echo “<a href=’moviesite.php?favmovie=$myfavmovie’>”; echo “Click here to see information about my favorite movie!”; echo “</a>”; echo “<br>”; echo “<a href=’moviesite.php?movienum=5’>”; echo “Click here to see my top 5 movies.”; echo “</a>”; echo “<br>”; echo “<a href=’moviesite.php?movienum=10’>”; echo “Click here to see my top 10 movies.”; echo “</a>”; ?> </body> </html> 2. Now modify moviesite.php as shown: <?php session_start(); //check to see if user has logged in with a valid password if ($_SESSION[‘authuser’] != 1) { echo “Sorry, but you don’t have permission to view this page, you loser!”; 63 Creating PHP Pages Using PHP5 06_579665 ch02.qxd 12/30/04 8:10 PM Page 63 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com exit(); } ?> <html> <head> <title>My Movie Site</title> </head> <body> <?php include “header.php”; ?> <?php function listmovies_1() { echo “1. Life of Brian<br>”; echo “2. Stripes<br>”; echo “3. Office Space<br>”; echo “4. The Holy Grail<br>”; echo “5. Matrix<br>”; } function listmovies_2() { echo “6. Terminator 2<br>”; echo “7. Star Wars<br>”; echo “8. Close Encounters of the Third Kind<br>”; echo “9. Sixteen Candles<br>”; echo “10. Caddyshack<br>”; } if (isset($_REQUEST[‘favmovie’])) { echo “Welcome to our site, “; echo $_SESSION[‘username’]; echo “! <br>”; echo “My favorite movie is “; echo $_REQUEST[‘favmovie’]; echo “<br>”; $movierate = 5; echo “My movie rating for this movie is: “; echo $movierate; } else { echo “My top “; echo $_REQUEST[‘movienum’]; echo “ movies are:”; echo “<br>”; listmovies_1(); if ($_REQUEST[‘movienum’] == 10) listmovies_2(); } ?> </body> </html> 3. Now you must go through the login.php file before you can see your changes. Log in as Joe and use the password 12345. Your movie1.php page should look like the one in Figure 2-13. 4. Click the “5 Movies” link. Your screen should look like Figure 2-14. 5. Go back and click the “Top 10” link; your screen will look like the one in Figure 2-15. 64 Chapter 2 06_579665 ch02.qxd 12/30/04 8:10 PM Page 64 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Figure 2-13 Figure 2-14 65 Creating PHP Pages Using PHP5 06_579665 ch02.qxd 12/30/04 8:10 PM Page 65 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Figure 2-15 How It Works This has been a rudimentary look at how to use functions, but you can see how they work. The movie1.php page gave users the option of looking at 5 or 10 of your favorite movies. Whichever link they choose sets the value for $movienum. In addition, moviesite.php accomplishes several other tasks: ❑ It sets up the functions listmovies_1() and listmovies_2(), which prints a portion of the total top 10 list. ❑ You also added this line: if (isset($_REQUEST[‘favmovie’])) { The isset function checks to see if a variable has been set yet (this doesn’t check the value, just whether or not it has been used). You didn’t want to show users the information about your favorite movie if they didn’t click on the link to see it, so you used if/else to take it right outta there. If the variable favmovie has not yet been sent, the program jumps on down to the else portion. ❑ The script performs another if statement to check the value of movienum to run the correct corresponding functions. ❑ It also references the movienum variable for the title of the list, so the program displays the cor- rect number of movies in the list. 66 Chapter 2 06_579665 ch02.qxd 12/30/04 8:10 PM Page 66 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com As you get more advanced in your PHP programming skills, you might store a list of all your favorite movies in a database and reference them that way, changing your listmovies() function to list only one movie at a time and running the function listmovies() a number of times. You could also give your users the option of choosing how many movies they want displayed, perhaps through a drop- down box or radio buttons. That would be your new movienum variable. All About Arrays You’ve learned about variables and how they are used, but what if you need to have more than one value assigned to that variable? That, my friend, is a good old-fashioned array. Arrays are nothing more than lists of information mapped with keys and stored under one variable name. For example, you can store a person’s name and address or a list of states in one variable. Arrays can be a hard thing to wrap your brain around, so let’s take a visual approach. Say you see a man sitting at a table at a local restaurant. He has several characteristics that are unique to him, such as first name, last name, and age. You could easily store his pertinent information in three variables, $firstname, $lastname, and $age. Now, suppose his wife sits down to join him. How can you store her information? If you use the same variable names, how will you know which is her information and which is her husband’s? This is where arrays come in. You can store all of his information under one variable, and all of her information under another. If you put all the information in a chart, it would look like this: First Name Last Name Age Husband Albert Einstein 124 Wife Mileva Einstein 123 An array is just a row of information, and the “keys” are the column headers. Keys are identifiers to help keep the information organized and easy to use. In this instance, if you didn’t have column headers, you wouldn’t know what each of those variables represented. Now let’s see how you can use arrays in PHP syntax. Array Syntax With an array, you can store a person’s name and age under one variable name, like this: <?php $husband = array(“firstname”=>”Albert”, “lastname”=>”Einstein”, “age”=>”124”); echo $husband[“firstname”]; ?> 67 Creating PHP Pages Using PHP5 06_579665 ch02.qxd 12/30/04 8:10 PM Page 67 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Notice how you use => instead of = when assigning values to keys of arrays. This gives you an output of “Albert” and all the values are still stored in the variable name husband. You can also see how you keep track of the information inside the variable with the use of keys such as “firstname” and “lastname.” You can also set an array value in the following way: <?php $husband[“firstname”] = “Albert”; $husband[“lastname”] = “Einstein”; $husband[“age”] = 124; ?> This is the equivalent of the previous example. You can also have arrays within arrays (also known as multi-dimensional arrays). In the earlier example, you had two people sitting at one table. What if you pulled up another table and added a few more peo- ple to the mix? How in the heck would you store everyone’s information and keep it all separate and organized? Like this! <?php $table1 = array(“husband” => array(“firstname”=>”Albert”, “lastname”=>”Einstein”, “age”=>124), “wife” => array(“firstname”=>”Mileva”, “lastname”=>”Einstein”, “age”=>123)); //do the same for each table in your restaurant ?> Then if someone asks you, “Hey, what are the first names of the couple sitting at table one?,” you can easily print the information with a few simple echo statements: <?php echo $table1[“husband”][“firstname”]; echo “ & “; echo $table1[“wife”][“firstname”]; ?> This script would produce the output “Albert & Mileva.” If you want to simply store a list and not worry about the particular order, or what each value should be mapped to (such as a list of states or flavors of shaved ice), you don’t need to explicitly name the keys; PHP will assign invisible internal keys for processing; numeric integers starting with 0. This would be set up as follows: <?php $flavor[] = “blue raspberry”; $flavor[] = “root beer”; $flavor[] = “pineapple”; ?> 68 Chapter 2 06_579665 ch02.qxd 12/30/04 8:10 PM Page 68 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com These would then be referenced like this: echo $flavor[0]; //outputs “blue raspberry” echo $flavor[1]; //outputs “root beer” echo $flavor[2]; //outputs “pineapple” Sorting Arrays PHP provides many easy ways to sort array values. The table that follows lists some of the more com- mon array-sorting functions, although you can find a more extensive list in Appendix C. Function Description arsort(array) Sorts the array in descending value order and maintains the key/value relationship asort(array) Sorts the array in ascending value order and maintains the key/value relationship rsort(array) Sorts the array in descending value order sort(array) Sorts the array in ascending value order Try It Out Sorting Arrays Before we go further, let’s do a quick test on sorting arrays so you can see how the array acts when it is sorted. Type the following program in your text editor and call it sorting.php. <?php $flavor[] = “blue raspberry”; $flavor[] = “root beer”; $flavor[] = “pineapple”; sort($flavor); print_r($flavor); ?> How It Works Notice anything weird in the preceding code? Yes, we’ve introduced a new function: print_r. This sim- ply prints out information about a variable so that people can read it. It is frequently used to check array values, specifically. The output would look like that in Figure 2-16. You can see that the sort() function has done what it’s supposed to and sorted the values in ascending alphabetical order. You can also see the invisible keys that have been assigned to each value (and reas- signed in this case). foreach Constructs PHP also provides a foreach command that applies a set of statements for each value in an array. What an appropriate name, eh? It works only on arrays, however, and will give you an error if you try to use it with another type of variable. 69 Creating PHP Pages Using PHP5 06_579665 ch02.qxd 12/30/04 8:10 PM Page 69 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Figure 2-16 Your syntax for the foreach command looks like this: <?php $flavor[] = “blue raspberry”; $flavor[] = “root beer”; $flavor[] = “pineapple”; echo “My favorite flavors are:<br>”; foreach ($flavor as $currentvalue) { //these lines will execute as long as there is a value in $flavor echo $currentvalue . “<br>\n”; } ?> This produces a list of each of the flavors in whatever order they appear in your array. When PHP is processing your array, it keeps track of what key it’s on with the use of an internal array pointer. When your foreach function is called, the pointer is at the ready, waiting patiently at the first key/value in the array. At the end of the function, the pointer has moved down through the list and remains at the end, or the last key/value in the array. The position of the pointer can be a helpful tool, one which we’ll touch on later in this chapter. Try It Out Adding Arrays In this exercise, you’ll see what happens when you add arrays to the moviesite.php file. You’ll also sort them and use the foreach construct. 70 Chapter 2 06_579665 ch02.qxd 12/30/04 8:10 PM Page 70 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com 1. Make the following highlighted changes to the moviesite.php file: <?php session_start(); //check to see if user has logged in with a valid password if ($_SESSION[‘authuser’] != 1) { echo “Sorry, but you don’t have permission to view this page, you loser!”; exit(); } ?> <html> <head> <title>My Movie Site</title> </head> <body> <?php include “header.php”; ?> <?php $favmovies = array(“Life of Brian”, “Stripes”, “Office Space”, “The Holy Grail”, “Matrix”, “Terminator 2”, “Star Wars”, “Close Encounters of the Third Kind”, “Sixteen Candles”, “Caddyshack”); //delete these lines: function listmovies_1() { echo “1. Life of Brian<br>”; echo “2. Stripes<br>”; echo “3. Office Space<br>”; echo “4. The Holy Grail<br>”; echo “5. Matrix<br>”; } function listmovies_2() { echo “6. Terminator 2<br>”; echo “7. Star Wars<br>”; echo “8. Close Encounters of the Third Kind<br>”; echo “9. Sixteen Candles<br>”; echo “10. Caddyshack<br>”; } //end of deleted lines if (isset($_REQUEST[‘favmovie’])) { echo “Welcome to our site, “; echo $_SESSION[‘username’]; echo “! <br>”; echo “My favorite movie is “; 71 Creating PHP Pages Using PHP5 06_579665 ch02.qxd 12/30/04 8:10 PM Page 71 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com [...]... Integers from - 327 68 to 327 67, use smallint ❑ Integers from -8388608 to 8388607, use mediumint ❑ Integers from -21 47483648 to 21 47483647, use int ❑ Integers from - 922 33 720 36854775808 to 922 33 720 36854775807, use bigint ❑ Integers from 0 to 25 5, use tinyint unsigned ❑ Integers from 0 to 65535, use smallint unsigned ❑ Integers from 0 to 1677 721 5, use mediumint unsigned ❑ Integers from 0 to 429 496 729 5, use int... functions are: ❑ mysql_ connect ("hostname", "user", "pass"): Connects to the MySQL server ❑ mysql_ select_db("database name"): Equivalent to the MySQL command USE; makes the selected database the active one ❑ 92 mysql_ query("query"): Used to send any type of MySQL command to the server Using PHP5 with MySQL Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com ❑ mysql_ fetch_rows("results... book fans and their passwords) Chapter 3 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com MySQL commands can be issued through the command prompt, as you did in Chapter 1 when you were installing it and granting permissions to users, or through PHP We primarily use PHP to issue commands in this book, and we will discuss more about this shortly MySQL Structure Because MySQL is... parameter allows storage of 0 to 1677 721 5.) bigint(length) Numeric field that stores integers from - 922 33 720 36854775808 to 922 33 720 36854775807 (Adding the unsigned parameter allows storage of 0 to 18446744073709551615.) tinytext Allows storage of up to 25 5 characters mediumtext Allows storage of up to 167 721 5 characters longtext Allows storage of up to 429 496 729 5 characters blob Equal to a text field,... available at its source Web site, which we invite you to read MySQL Syntax and Commands Although it is quite possible to access MySQL directly through a shell command prompt, for the purposes of this book, we are going to access it through PHP Regardless of the mode by which the MySQL server gets its information and requests, the syntax is basically the same Typically, you keep the MySQL commands in all caps,... password 123 45), and when you get the choice, click the link that lists the top 10 movies You should see something like Figure 2- 17 Figure 2- 17 73 Chapter 2 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com 4 Go back to movie1.php, and this time click the link that lists the movies sorted in alphabetical order This time, you should see something like Figure 2- 18 Figure 2- 18 How... database query ❑ mysql_ fetch_array("results variable from query"): Used to return several rows of the entire results of a database query ❑ mysql_ error(): Shows the error message that has been returned directly from the MySQL server You will most likely become very familiar with these commands, and many more You can also send any MySQL command to the server through PHP and the mysql_ query command, as in the... Fits with MySQL With the onset of PHP5, you need to take a few extra steps to convince PHP and MySQL to play well with each other Before your MySQL functions will be recognizable by PHP, make sure to enable MySQL in your php.ini file, which we covered in Chapter 1 You can use MySQL commands within PHP code almost as seamlessly as you do with HTML Numerous PHP functions work specifically with MySQL to... Mathematical functions can be performed on data in this field Quantity of a product on hand Using PHP5 with MySQL Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com MySQL Field Type Description Example int(length) unsigned Numeric field that stores positive integers (and zero) up to 429 496 729 5 The length parameter limits the number of digits that can be displayed Mathematical... http://www.simpopdf.com Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com 3 Using PHP5 with MySQL So now that you’ve done some really cool stuff with PHP in Chapter 2, such as using includes and functions, it’s time to make your site truly dynamic and show users some real data You may or may not have had experience with databases, so we’ll take a look at what MySQL is and how PHP can tap into . 2 06_579665 ch 02. qxd 12/ 30/04 8:10 PM Page 64 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Figure 2- 13 Figure 2- 14 65 Creating PHP Pages Using PHP5 06_579665 ch 02. qxd 12/ 30/04. sometimes you need to create your own customized functions. 62 Chapter 2 06_579665 ch 02. qxd 12/ 30/04 8:10 PM Page 62 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Try It. Movie!</title> </head> <body> <?php include “header.php”; ?> <?php 72 Chapter 2 06_579665 ch 02. qxd 12/ 30/04 8:10 PM Page 72 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com $myfavmovie

Ngày đăng: 13/08/2014, 12:21

Từ khóa liên quan

Mục lục

  • Beginning PHP5, Apache, and MySQL Web Development

    • Cover

    • Contents

    • Part I: Getting Started

      • Chapter 1: Configuring Your Installation

        • Projects in This Book

        • Brief Intro to PHP, Apache, MySQL, and Open Source

          • A Brief History of Open Source Initiatives

          • Why Open Source Rocks

          • How the Pieces of the AMP Module Work Together

            • Apache

            • PHP

            • MySQL

            • AMP Installers

            • Foxserv

            • PHPTriad

            • XAMPP

            • Configuring Your Apache Installation

              • Testing Your Installation

              • Customizing Your Installation

              • Adding PHP to the Equation

              • Document Root

              • Configuring Your PHP Installation

                • Testing Your Installation

                • Customizing Your Installation

                • Configuring PHP5 to Use MySQL

                • Configuring Your MySQL Installation

                  • Testing Your Installation

Tài liệu cùng người dùng

Tài liệu liên quan