Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 30 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
30
Dung lượng
544,84 KB
Nội dung
Chapter 2: Creating PHP Pages Using PHP6 61 ‘wife’ = > array(‘firstname’ = > ‘Mileva’, ‘lastname’ = > ‘Einstein’, ‘age’ = > 128)); // 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 $table[1][‘husband’][‘firstname’]; echo ‘ and ‘; echo $table[1][‘wife’][‘firstname’]; ? > This script would produce the output “ Albert and 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 ice cream), you don ’ t need to explicitly name the keys; PHP can automatically assign numeric keys with integers starting with 0. This would be set up as follows: < ?php $flavors[] = ‘blue raspberry’; $flavors[] = ‘root beer’; $flavors[] = ‘pineapple’; ? > These would then be referenced like this: < ?php echo $flavors[0]; //outputs “blue raspberry” echo $flavors[1]; //outputs “root beer” echo $flavors[2]; //outputs “pineapple” ? > Sorting Arrays A common task you may find yourself doing with arrays is sorting their values. PHP provides many functions that making sorting array values easy. Here are just a few common array - sorting functions, although you will find a more extensive list in Appendix C . sort($array) : Sorts an array in ascending value order rsort($array) : Sorts an array in descending value order asort($array) : Sorts an array in ascending value order while maintaining the key/value relationship arsort($array) : Sorts an array in descending value order while maintaining the key/value relationship ❑ ❑ ❑ ❑ c02.indd 61c02.indd 61 12/10/08 5:46:46 PM12/10/08 5:46:46 PM 62 Part I: Movie Review Web Site 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 $flavors[] = ‘blue raspberry’; $flavors[] = ‘root beer’; $flavors[] = ‘pineapple’; sort($flavors); print_r($flavors); ? > How It Works Notice anything weird in the preceding code? Yes, we ’ ve introduced a new function: print_r() . This simply 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 - 17 . Figure 2-17 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 keys that have been automatically assigned to each value (and reassigned by sort() in this case). c02.indd 62c02.indd 62 12/10/08 5:46:46 PM12/10/08 5:46:46 PM Chapter 2: Creating PHP Pages Using PHP6 63 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? Your syntax for the foreach command looks like this: < ?php $flavors[] = ‘blue raspberry’; $flavors[] = ‘root beer’; $flavors[] = ‘pineapple’; echo ‘My favorite flavors are: < br/ > ’; foreach ($flavors as $current_flavor) { //these lines will execute as long as there are more values in $flavors echo $current_flavor ‘ < br/ > ‘; } ? > 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 by using an internal array pointer . When your foreach construct is called, the pointer is ready and waiting patiently at the first key/value in the array. At the end of the loop, the pointer has moved down through the list and remains at the end, or the last key/value in the array. 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. 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!”; exit(); } ? > < html > < head > < title > My Movie Site < ?php if (isset($_GET[‘favmovie’])) { echo ‘ - ‘; echo $_GET[‘favmovie’]; } ? > < /title > c02.indd 63c02.indd 63 12/10/08 5:46:47 PM12/10/08 5:46:47 PM 64 Part I: Movie Review Web Site < /head > < body > < ?php include ‘header.php’; ? > < ?php $favmovies = array(‘Life of Brian’, ‘Stripes’, ‘Office Space’, ‘The Holy Grail’, ‘Matrix’, ‘Terminator 2’, ‘Star Trek IV’, ‘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 Trek IV < 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($_GET[‘favmovie’])) { echo ‘Welcome to our site, ‘; echo $_SESSION[‘username’]; echo ‘! < br/ > ’; echo ‘My favorite movie is ‘; echo $_GET[‘favmovie’]; echo ‘ < br/ > ’; $movierate = 5; echo ‘My movie rating for this movie is: ‘; echo $movierate; } else { echo ‘My top 10 favorite movies are: < br/ > ’; if (isset($_GET[‘sorted’])) { sort($favmovies); } echo ‘ < ol > ’; foreach ($favmovies as $movie) { echo ‘ < li > ’; echo $movie; c02.indd 64c02.indd 64 12/10/08 5:46:47 PM12/10/08 5:46:47 PM Chapter 2: Creating PHP Pages Using PHP6 65 echo ‘ < /li > ’; } echo ‘ < /ol > ’; // delete these lines: echo ‘My top ‘; echo $_GET[‘movienum’]; echo ‘ movies are:’; echo ‘ < br/ > ’; listmovies_1(); if ($_GET[‘movienum’] == 10) { listmovies_2(); } // end of deleted lines } ? > < /body > < /html > 2. Then change movie1.php as shown here: < ?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!’; 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 > ”; ? > < br/ > < ! delete these lines c02.indd 65c02.indd 65 12/10/08 5:46:47 PM12/10/08 5:46:47 PM 66 Part I: Movie Review Web Site < a href=”moviesite.php?movienum=5” > Click here to see my top 5 movies. < /a > < br/ > < a href=”moviesite.php?movienum=10” > Click here to see my top 10 movies. < /a > end of deleted lines > < a href=”moviesite.php” > Click here to see my 10 movies. < /a > < br/ > < a href=”moviesite.php?sorted=true” > Click here to see my top 10 movies sorted alphabetically. < /a > < /body > < /html > 3. Now log in with the login.php file (log in as Joe with password 12345), and when you get the choice, click the link that lists the top 10 movies. You should see something like Figure 2 - 18 . Figure 2-18 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 - 19 . c02.indd 66c02.indd 66 12/10/08 5:46:47 PM12/10/08 5:46:47 PM Chapter 2: Creating PHP Pages Using PHP6 67 How It Works You first put the movie list in one variable, $favmovies , with the array function. Then you were able to list the movies individually, using the foreach construct in moviesite.php . You also added a link that would allow users to show the list sorted alphabetically, by adding a variable named $_GET[sorted] . When this variable was set to true , the sort() function executed, and you passed that true variable through the URL in the link. You may have noticed a shortcoming in the program . . . okay, you may have noticed many shortcomings, but one in particular stands out. You can no longer control how many movies are shown in your list. You are stuck with showing the total number of movies in the array. There ’ s a way to fix that, which is what we ’ ll talk about next. While You ’ re Here . . . You ’ ve seen that foreach will take an action on each element of an array until it reaches the end, but you can also take an action on just some of the elements in an array, with the while statement. A while statement tells the server to execute a series of statements repeatedly as long as a given condition is true. Here ’ s an example of how you would use the while command. This code simply counts from 1 to 5 and prints each number on a separate line. First a variable $num is set to 0. This variable is then increased by 1 each time through the loop. The while checks to see that the value of $num is less than 5. After five times through the loop, the value of $num is 6, so the loop ends. Figure 2-19 c02.indd 67c02.indd 67 12/10/08 5:46:48 PM12/10/08 5:46:48 PM 68 Part I: Movie Review Web Site < ?php $num = 0; while ($num < 5) { $num = $num + 1; echo $num; echo ‘ < br/ > ’; } ? > The following code does the same thing, but it uses a do / while loop instead. This code works exactly the same way, except that the condition is checked at the end of the loop. With a while loop, it is possible for the condition to be false and the associated code never to execute. But with the check at the end, as with a do / while loop, then the commands inside the loop will always be executed at least once. < ?php $num = 0; do { $num = $num + 1; echo $num; echo ‘ < br/ > ’; } while ($num < 5); ? > Try It Out Using the while Function This exercise allows users to tell you how many movies they want to see, and enables you to number the list as you did before, using the while function. 1. Make the following changes to your movie1.php program: < ?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!’; 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\” > ”; c02.indd 68c02.indd 68 12/10/08 5:46:49 PM12/10/08 5:46:49 PM Chapter 2: Creating PHP Pages Using PHP6 69 echo “Click here to see information about my favorite movie!”; echo “ < /a > ”; ? > < br/ > < ! delete these lines < a href=”moviesite.php?” > Click here to see my top 10 movies. < /a > < br/ > < a href=”moviesite.php?sorted=true” > Click here to see my top 10 movies sorted alphabetically. < /a > end deleted lines > < br/ > Or choose how many movies you would like to see: < br/ > < form method=”post” action=”moviesite.php” > < p > Enter number of movies (up to 10): < input type=”text” name=”num” maxlength=”2” size=”2”/ > < br/ > Check to sort them alphabetically: < input type=”checkbox” name=”sorted” / > < /p > < input type=”submit” name=”submit” value=”Submit”/ > < /form > < /body > < /html > 2. Make the following changes to moviesite.php : < ?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!”; exit(); } ? > < html > < head > < title > My Movie Site < ?php if (isset($_GET[‘favmovie’])) { echo ‘ - ‘; echo $_GET[‘favmovie’]; } ? > < /title > < /head > < body > < ?php include ‘header.php’; ? > < ?php c02.indd 69c02.indd 69 12/10/08 5:46:50 PM12/10/08 5:46:50 PM 70 Part I: Movie Review Web Site $favmovies = array(‘Life of Brian’, ‘Stripes’, ‘Office Space’, ‘The Holy Grail’, ‘Matrix’, ‘Terminator 2’, ‘Star Trek IV’, ‘Close Encounters of the Third Kind’, ‘Sixteen Candles’, ‘Caddyshack’); if (isset($_GET[‘favmovie’])) { echo ‘Welcome to our site, ‘; echo $_SESSION[‘username’]; echo ‘! < br/ > ’; echo ‘My favorite movie is ‘; echo $_GET[‘favmovie’]; echo ‘ < br/ > ’; $movierate = 5; echo ‘My movie rating for this movie is: ‘; echo $movierate; } else { echo ‘My top ‘ . $_POST[‘num’] . ‘ favorite movies’; if (isset($_POST[‘sorted’])) { sort($favmovies); echo ‘ (sorted alphabetically) ‘; } echo ‘are: < br/ > ’; // delete these lines echo ‘ < ol > ’; foreach ($favmovies as $movie) { echo ‘ < li > ’; echo $movie; echo ‘ < /li > ’; } echo ‘ < /ol > ’; // end of deleted lines $numlist = 0; echo ‘ < ol > ’; while ($numlist < $_POST[‘num’]) { echo ‘ < li > ’; echo $favmovies[$numlist]; echo ‘ < /li > ’; $numlist = $numlist + 1; } echo ‘ < /ol > ’; } ? > < /body > < /html > c02.indd 70c02.indd 70 12/10/08 5:46:50 PM12/10/08 5:46:50 PM [...]... c03.indd 84 12/10/08 5:46:06 PM Chapter 3: Using PHP with MySQL How PHP Fits with My SQL Since the onset of PHP6, 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, 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... specifically with MySQL to make your life easier; you can find a comprehensive list in Appendix C Some of the more commonly used functions are: ❑ ❑ mysql_ connect([$host[, $username[, $password]]]): Connects to the MySQL server and returns a resource which is used to reference the connection mysql_ select_db($database[, $resource]): Equivalent to the MySQL command USE and sets the active database ❑ mysql_ query($query[,... //connect to MySQL $db = mysql_ connect(‘localhost’, ‘bp6am’, ‘bp6ampass’) or die (‘Unable to connect Check your connection parameters.’); //create the main database if it doesn’t already exist $query = ‘CREATE DATABASE IF NOT EXISTS moviesite’; mysql_ query($query, $db) or die (mysql_ error($db)); //make sure our recently created database is the active one mysql_ select_db(‘moviesite’, $db) or die (mysql_ error($db));... those.) By the end of this chapter, you will be able to: ❑ Understand what a MySQL database is ❑ View data contained in the MySQL database ❑ Connect to the database from your web site ❑ Pull specific information out of the database, right from your web site ❑ Use third-party software to easily manage tables ❑ Use the source web site to troubleshoot problems you may encounter Although some of this information... c03.indd 81 12/10/08 5:46:05 PM Part I: Movie Review Web Site If your field requirements do not fall into any of these categories, check Appendix D for a complete list of all available field types You can also check the documentation at the MySQL web site (www .mysql. com) if you are still unsure about what type of field you need null/not null Your MySQL server also wants to know whether or not the field... any MySQL command to the server through PHP, using the mysql_ query command, as shown in the following example You do this by sending the straight text through PHP, either through a variable or through the mysql_ query command directly, like this: $results = mysql_ query(‘SELECT * FROM TABLE’); But one could argue it is better to do it in two steps, like this: $query = ‘SELECT * FROM TABLE’; $results = mysql_ query($query);... Review Web Site Connecting to the My SQL Ser ver Before you can do anything with MySQL, you must first connect to the MySQL server using your specific connection values Connection variables consist of the following parameters: ❑ Hostname: In our case, this is localhost because everything has been installed locally You will need to change this to whatever host is acting as your MySQL server, if MySQL. .. with the PHP function called mysql_ connect() As with all of your PHP /MySQL statements, you can either put the information into variables or leave it as text in your MySQL query Here’s how you would do it with variables: $host $user $pass $db = = ‘localhost’; = ‘bp6am’; = ‘bp6ampass’; mysql_ connect($host, $user, $pass); The following statement has the same effect: $db = mysql_ connect(‘localhost’, ‘bp6am’,... action later in the chapter Other Parameters You can make other specifications when creating your database, but those are for more advanced MySQL users For a complete list of these parameters, we encourage you to visit the MySQL web site, www .mysql. com Types of MySQL Tables and Storage Engines Now that you understand some of the general features of tables, you should know that there are two different... movie_year) ) ENGINE=MyISAM’; mysql_ query($query, $db) or die (mysql_ error($db)); //create the movietype table $query = ‘CREATE TABLE movietype ( movietype_id TINYINT UNSIGNED NOT NULL AUTO_INCREMENT, movietype_label VARCHAR(100) NOT NULL, PRIMARY KEY (movietype_id) ) 87 c03.indd 87 12/10/08 5:46:07 PM Part I: Movie Review Web Site ENGINE=MyISAM’; mysql_ query($query, $db) or die (mysql_ error($db)); //create . Understand what a MySQL database is . View data contained in the MySQL database . Connect to the database from your web site . Pull specific information out of the database, right from your web site. book fans and their passwords) in a MySQL database. ❑ ❑ ❑ ❑ ❑ ❑ c03.indd 77c03.indd 77 12/10/08 5:46:03 PM12/10/08 5:46:03 PM 78 Part I: Movie Review Web Site MySQL commands can be issued through. chapter, our goal was to give you enough ammunition to get started on your own web site. Our hope is that you are beginning to realize the power of PHP and how easy it is to jump in and get started.