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
582,49 KB
Nội dung
Chapter 5: Form Elements: Letting the User Work with Data 151 How It Works This set of scripts is designed around a simple idea: passing data through multiple scripts from form to form. The key to this has been input elements with their type attribute set to hidden . These fields are not displayed by the browser to the user, but their values are submitted with the rest of the form fields ’ data. This is but one way to pass data between forms, though it is very common. Summary You ’ ve learned a lot of about forms in this chapter. Forms are composed of fields. Each field type has a specific purpose and allows a certain data type to be entered. Text fields can be used to enter text or numeric data. Lists can be used to enter any type of data and have a limited set of possible values. Lists are a good way to drive user input when multiple choices are available. Check boxes are good for true or false values. Figure 5-9 c05.indd 151c05.indd 151 12/10/08 5:45:44 PM12/10/08 5:45:44 PM Part I: Movie Review Web Site 152 Exercises See how you might accomplish the following: 1. Create a form and a processing page that let you choose a rating (stars, thumbs up, number from 1 to 5, whatever), and provide comments for a movie. 2. Create a form with several text input boxes that allow you to populate the options of a select field on a subsequent page. 3. Create a calculator form that takes two numbers and calculates their sum. c05.indd 152c05.indd 152 12/10/08 5:45:45 PM12/10/08 5:45:45 PM 6 Letting the User Edit the Database Retrieving data from a database is all well and good when you ’ ve first fed the database some data. But databases don ’ t generate their own content, and only a few get fed data by other systems, such as integrated systems. What this means is that you have to feed your system with data that comes from PHP. For our purposes here, and from what you ’ ve seen in previous chapters, all interaction with the database uses SQL. You already know the basic SQL syntax to put your own data in a table and retrieve it for users to see. But now, let ’ s look at the other side of the equation — data processing. This chapter covers database editing, including: Adding entries, which is quite simple — but you will find that adding entries in a relational database is yet another exercise . Deleting entries without corrupting the database structure and referential integrity . Modifying entries to replace some existing fields with new content in an existing record . Preparing the Battlefield We ’ ll continue to use the moviesite database from the previous chapters here. First you ’ ll start by creating the administrative page that lists the movies and people in your database and provides links for you to manage them. Then you will create the auxiliary pages that will let you add and delete movie records. ❑ ❑ ❑ c06.indd 153c06.indd 153 12/10/08 5:47:47 PM12/10/08 5:47:47 PM 154 Part I: Movie Review Web Site Try It Out Setting Up the Environment First, you need a start page. Follow these steps to create one: 1. Create a file named admin.php , and enter the following code: < ?php $db = mysql_connect(‘localhost’, ‘bp6am’, ‘bp6ampass’) or die (‘Unable to connect. Check your connection parameters.’); mysql_select_db(‘moviesite’, $db) or die(mysql_error($db)); ? > < html > < head > < title > Movie database < /title > < style type=”text/css” > th { background-color: #999;} .odd_row { background-color: #EEE; } .even_row { background-color: #FFF; } < /style > < /head > < body > < table style=”width:100%;” > < tr > < th colspan=”2” > Movies < a href=”movie.php?action=add” > [ADD] < /a > < /th > < /tr > < ?php $query = ‘SELECT * FROM movie’; $result = mysql_query($query, $db) or die (mysql_error($db)); $odd = true; while ($row = mysql_fetch_assoc($result)) { echo ($odd == true) ? ‘ < tr class=”odd_row” > ’ : ‘ < tr class=”even_row” > ’; $odd = !$odd; echo ‘ < td style=”width:75%;” > ’; echo $row[‘movie_name’]; echo ‘ < /td > < td > ’; echo ‘ < a href=”movie.php?action=edit & id=’ . $row[‘movie_id’] . ‘” > [EDIT] < /a > ’; echo ‘ < a href=”delete.php?type=movie & id=’ . $row[‘movie_id’] . ‘” > [DELETE] < /a > ’; echo ‘ < /td > < /tr > ’; } ? > < tr > < th colspan=”2” > People < a href=”people.php?action=add” > [ADD] < /a > < /th > < /tr > < ?php $query = ‘SELECT * FROM people’; $result = mysql_query($query, $db) or die (mysql_error($db)); c06.indd 154c06.indd 154 12/10/08 5:47:48 PM12/10/08 5:47:48 PM Chapter 6: Letting the User Edit the Database 155 $odd = true; while ($row = mysql_fetch_assoc($result)) { echo ($odd == true) ? ‘ < tr class=”odd_row” > ’ : ‘ < tr class=”even_row” > ’; $odd = !$odd; echo ‘ < td style=”width: 25%;” > ’; echo $row[‘people_fullname’]; echo ‘ < /td > < td > ’; echo ‘ < a href=”people.php?action=edit & id=’ . $row[‘people_id’] . ‘” > [EDIT] < /a > ’; echo ‘ < a href=”delete.php?type=people & id=’ . $row[‘people_id’] . ‘” > [DELETE] < /a > ’; echo ‘ < /td > < /tr > ’; } ? > < /table > < /body > < /html > 2. Now open the file in your browser. You will see the page as shown in Figure 6 - 1 . Figure 6-1 c06.indd 155c06.indd 155 12/10/08 5:47:48 PM12/10/08 5:47:48 PM 156 Part I: Movie Review Web Site All links are broken at the moment, but do not worry; that ’ s perfectly normal, because you haven ’ t yet created the other pages. How It Works You must always have a central administration interface that allows you to perform actions on the data and easily see the content. This script provides that admin interface. It shows you all the data and allows you to manage everything in sight. So how does it do it? As in Chapter 4, here, you connect to the database and display its contents. The code generates an HTML table that holds the name of each movie and person, along with ADD, EDIT, and DELETE links. Odd and even rows of the table appear in different colors, as a visual cue that helps line up the entry with the EDIT and DELETE links. Before the start of each while loop that is responsible for listing the results of the database query, the variable $odd is set to true . How the tr tag is generated upon each iteration depends on the value of $odd , and then the value of $odd is toggled in preparation for the next iteration of the loop. Inserting a Record in a Relational Database Databases often hold more than just one table. All those tables can be totally independent, but that would be like using your car to store things in the trunk, but never to drive around in. Usually the tables are related to one another in some manner. In old systems in which relational databases didn ’ t exist, every row held all the information possible. Imagine your system running with only one table holding all the information for your application. Your movie table, for example, would store all the data about the actors and the directors and the movie types. Each record would have all this information specified. Now suppose that one day you were to decide that a movie category should be changed from “ action ” to “ adventure. ” You would then have to go through all the records in the table records to change the movie type label. The possibility for mistakes is exponentially greater as well! This is not the case in modern relational database management systems (RDBMS); you can create a movietype table storing a reference of all the possible movie types, and then link movies to the relevant movie type. To link different tables, you use a primary key/foreign key pair. A primary key is a value or set of values that can be used to uniquely identify each record in a table. The primary key of the movietype table is the numeric identification of each type of movie stored in the movietype_id field. For example, in your database, the id 1 references comedy. The foreign key is a value in another table that can be used to reference back to the primary key. The reference in the movie table is to the movietype primary key. In the following exercise, you use PHP and SQL to insert a movie in your database. This movie is of a known movie type from the movietype reference table. c06.indd 156c06.indd 156 12/10/08 5:47:49 PM12/10/08 5:47:49 PM Chapter 6: Letting the User Edit the Database 157 Try It Out Inserting a Movie with Known Movie Type and People This time, let ’ s do something a bit more complicated. You ’ ll be able to add a movie to the system while specifying an existing movie type and existing actor and director. 1. Create a new empty file with your text editor, and enter the following code. Save it as movie.php . < ?php $db = mysql_connect(‘localhost’, ‘bp6am’, ‘bp6ampass’) or die (‘Unable to connect. Check your connection parameters.’); mysql_select_db(‘moviesite’, $db) or die(mysql_error($db)); ? > < html > < head > < title > Add Movie < /title > < /head > < body > < form action=”commit.php?action=add & type=movie” method=”post” > < table > < tr > < td > Movie Name < /td > < td > < input type=”text” name=”movie_name”/ > < /td > < /tr > < tr > < td > Movie Type < /td > < td > < select name=”movie_type” > < ?php // select the movie type information $query = ‘SELECT movietype_id, movietype_label FROM movietype ORDER BY movietype_label’; $result = mysql_query($query, $db) or die(mysql_error($db)); // populate the select options with the results while ($row = mysql_fetch_assoc($result)) { foreach ($row as $value) { echo ‘ < option value=”’ . $row[‘movietype_id’] . ‘” > ’; echo $row[‘movietype_label’] . ‘ < /option > ’; } } ? > < /select > < /td > < /tr > < tr > < td > Movie Year < /td > < td > < select name=”movie_year” > c06.indd 157c06.indd 157 12/10/08 5:47:49 PM12/10/08 5:47:49 PM 158 Part I: Movie Review Web Site < ?php // populate the select options with years for ($yr = date(“Y”); $yr > = 1970; $yr ) { echo ‘ < option value=”’ . $yr . ‘” > ’ . $yr . ‘ < /option > ’; } ? > < /select > < /td > < /tr > < tr > < td > Lead Actor < /td > < td > < select name=”movie_leadactor” > < ?php // select actor records $query = ‘SELECT people_id, people_fullname FROM people WHERE people_isactor = 1 ORDER BY people_fullname’; $result = mysql_query($query, $db) or die(mysql_error($db)); // populate the select options with the results while ($row = mysql_fetch_assoc($result)) { foreach ($row as $value) { echo ‘ < option value=”’ . $row[‘people_id’] . ‘” > ’; echo $row[‘people_fullname’] . ‘ < /option > ’; } } ? > < /select > < /td > < /tr > < tr > < td > Director < /td > < td > < select name=”movie_director” > < ?php // select director records $query = ‘SELECT people_id, people_fullname FROM people WHERE people_isdirector = 1 ORDER BY people_fullname’; $result = mysql_query($query, $db) or die(mysql_error($db)); // populate the select options with the results while ($row = mysql_fetch_assoc($result)) { foreach ($row as $value) { echo ‘ < option value=”’ . $row[‘people_id’] . ‘” > ’; c06.indd 158c06.indd 158 12/10/08 5:47:49 PM12/10/08 5:47:49 PM Chapter 6: Letting the User Edit the Database 159 echo $row[‘people_fullname’] . ‘ < /option > ’; } } ? > < /select > < /td > < /tr > < tr > < td colspan=”2” style=”text-align: center;” > < input type=”submit” name=”submit” value=”Add” / > < /td > < /tr > < /table > < /form > < /body > < /html > 2. Create a new empty file named commit.php , and enter the following code: < ?php $db = mysql_connect(‘localhost’, ‘bp6am’, ‘bp6ampass’) or die (‘Unable to connect. Check your connection parameters.’); mysql_select_db(‘moviesite’, $db) or die(mysql_error($db)); ? > < html > < head > < title > Commit < /title > < /head > < body > < ?php switch ($_GET[‘action’]) { case ‘add’: switch ($_GET[‘type’]) { case ‘movie’: $query = ‘INSERT INTO movie (movie_name, movie_year, movie_type, movie_leadactor, movie_director) VALUES (“’ . $_POST[‘movie_name’] . ‘”, ‘ . $_POST[‘movie_year’] . ‘, ‘ . $_POST[‘movie_type’] . ‘, ‘ . $_POST[‘movie_leadactor’] . ‘, ‘ . $_POST[‘movie_director’] . ‘)’; break; } break; c06.indd 159c06.indd 159 12/10/08 5:47:50 PM12/10/08 5:47:50 PM 160 Part I: Movie Review Web Site } if (isset($query)) { $result = mysql_query($query, $db) or die(mysql_error($db)); } ? > < p > Done! < /p > < /body > < /html > 3. Open your browser on the admin.php page, and click the ADD link in the movie table ’ s header. You should see on the screen the form in which you can enter movie information. 4. Add a movie named “ Test ” with a random movie type, actor, and director, as shown in Figure 6 - 2 . Figure 6-2 5. Click the Add button, and you will see the confirmation message shown in Figure 6 - 3 . c06.indd 160c06.indd 160 12/10/08 5:47:50 PM12/10/08 5:47:50 PM [...]... Database Try It Out Deleting a Single Record Before asking PHP to delete anything though MySQL, let’s first try it ourselves to familiarize ourselves with the DELETE statement 1 Open a console window and connect to the MySQL server with the command-line program, as in Chapter 1: “C:\Program Files \MySQL\ MySQL Server 5.0\bin \mysql. exe” -u root -p 2 Select the movies database by entering the following: USE movies;... $result = mysql_ query($query, $db) or die (mysql_ error($db)); $query = ‘DELETE FROM people WHERE people_id = ‘ $_GET[‘id’]; $result = mysql_ query($query, $db) or die (mysql_ error($db)); ?> Your person has been deleted Return to Index . $_GET[‘id’]; $result = mysql_ query($query, $db) or die (mysql_ error($db)); $query = ‘DELETE FROM people WHERE people_id = ‘ . $_GET[‘id’]; $result = mysql_ query($query, $db) or die (mysql_ error($db)); ?. $_GET[‘id’]; $result = mysql_ query($query, $db) or die (mysql_ error($db)); $query = ‘DELETE FROM people WHERE people_id = ‘ . $_GET[‘id’]; $result = mysql_ query($query, $db) or die (mysql_ error($db)); . < ?php $db = mysql_ connect(‘localhost’, ‘bp6am’, ‘bp6ampass’) or die (‘Unable to connect. Check your connection parameters.’); mysql_ select_db(‘moviesite’, $db) or die (mysql_ error($db)); ?