Then you will create the auxiliary pages that will let you add and delete movie records... The code generates an HTML table that holds the name of each movie and person, along with ADD,
Trang 1How 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
Summar y
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
Trang 2Exercises
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
Trang 36
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
❑
❑
❑
Trang 4Try 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.’);
$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” >
$query = ‘SELECT * FROM people’;
$result = mysql_query($query, $db) or die (mysql_error($db));
Trang 5
/body >
< /html >
2 Now open the file in your browser You will see the page as shown in Figure 6 - 1
Figure 6-1
Trang 6All 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
Inser ting 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
Trang 7Try 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
$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 resultswhile ($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” >
Trang 8< ?php
// populate the select options with years
for ($yr = date(“Y”); $yr > = 1970; $yr ) {
echo ‘ < option value=”’ $yr ‘” > ’ $yr ‘ < /option >
// 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 >
// populate the select options with the results
while ($row = mysql_fetch_assoc($result)) {
foreach ($row as $value) {
echo ‘ < option value=”’ $row[‘people_id’] ‘” >
Trang 9echo $row[‘people_fullname’] ‘ < /option >
}}
? < /select > < /td >
< /tr > < tr >
< td colspan=”2” style=”text-align: center;” >
< input type=”submit” name=”submit” value=”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;
Trang 103 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
Trang 11to chose a predetermined value
To generate the list of movie types, you simply query the database, retrieve the records and display the types, and reference their primary key as the item value Each known movie type will have an item in the select box
Back in Chapter 2, you were introduced to the while loop and the foreach loop The year list is a selection of years from 1970 to the current year, and is generated with a new type of loop, the for loop
When using these types of loops, you should know that for loops will offer a more restricted way of setting up code for repetitive execution They begin with the keyword for and then a set of three statements: first a variable set to an initial value to be used as the loop ’ s counter, then a conditional
Figure 6-3
Trang 12statement, and finally the increment in which the counter value is adjusted after each execution of the
loop The code block that gets executed is bracketed and follows the for statement, following this
syntax:
for (initialize; condition; increment) {
// code
}
The initial value of $yr is set to the current year with the help of the date() function The condition is
set so the loop will continue executing as long as the value $yr is greater than or equal to 1970 Each
time the loop executes, the value of $yr is reduced by 1 The code that is repeatedly executed uses the
value of $yr to place the years into the select ’ s items
for loops are more restricted than the other loops, in that the variable is intended only to act as a
counter mechanism It wouldn ’ t be good practice to change its value within the code block! This is
compared to the do - while and while loops, where the value is intentionally changed in the code
block to affect the loop ’ s behavior
The same steps followed to generate the movie type listing are followed for the actor and director
select fields A query is sent to the database, the results are retrieved, and the person is displayed with
the primary key as the item value The only difference between the queries is the WHERE clause that
filters the retrieved results to first just the actors and then just the directors
Now that your form is ready, you need to have a script that uses this data to create records This is the
purpose of commit.php As you can see, the switch statement using the $_GET[‘action’] value is
totally useless for now, but in the next exercises you will add a lot of code to the movie.php script so
you can use it to edit the movies Then commit.php ’ s switch will be more important
Deleting a Record
Deleting records is easy (perhaps a bit too easy at times) Deleting always means losing data, so be
especially careful when doing so To delete a record you need to point to the record through a set of
conditions in a WHERE statement Once this statement is executed, there is no turning back Records are
deleted without hope of return; that ’ s why we advise caution when using the DELETE statement MySQL
deletes everything that matches the query, and forgetting one little thing in your WHERE clause could
have disastrous consequences
Because deleting records is irrevocable, you may find it beneficial to make sure your WHERE clause causes
the correct records to be selected first You can use MySQL ’ s command - line program, first discussed in
Chapter 1, to issue a SELECT statement and then review the result set that is returned Then, when you
are certain the correct records are selected, you can prepare your DELETE statement
Trang 13Try 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;
3 Test the WHERE clause using a SELECT statement:
SELECT * FROM movie WHERE movie_id = 4;
4 Verify the WHERE clause is correct by examining the returned results to see that it is indeed the record you wish to delete
5 Delete the record by using a DELETE statement:
DELETE FROM movie WHERE movie_id = 4;
6 See that the record was deleted by reissuing the SELECT statement:
SELECT * FROM movie WHERE movie_id = 4;
To avoid that problem, you can use a more elaborate form of the DELETE statement, the Cascade Delete ,
as discussed in the following section
Trang 14Try It Out Cascade Delete
Now that you know how to use DELETE , you will implement it to delete a known person from your
application ’ s database Because you store references to known people in the movie table, you will
need to update the movie table content so you don ’ t reference deleted people (The update - specific
exercises come next in this chapter.) Deleting the person only would be like throwing away your car
keys and expecting your parking spot to be empty You need to make sure no reference to a deleted
record is left in the remaining data
Follow these steps to implement the Cascade Delete:
1 Create a new text file named delete.php , and enter the following code:
< ?php
$db = mysql_connect(‘localhost’, ‘bp6am’, ‘bp6ampass’) or
die (‘Unable to connect Check your connection parameters.’);
echo ‘ < a href=”’ $_SERVER[‘REQUEST_URI’] ‘ & do=1” > yes < /a > ‘;
echo ‘or < a href=”admin.php” > no < /a >
< p style=”text-align: center;” > Your person has been deleted
< a href=”movie_index.php” > Return to Index < /a > < /p >
Trang 15< a href=”movie_index.php” > Return to Index < /a > < /p >
< ?php break;
}}
?
2 Open admin.php in your browser again, and note the DELETE links next to each movie or person
3 Try deleting the test movie you added in the previous exercise by clicking the DELETE link
next to its name You will be asked for confirmation, as in Figure 6 - 4
Figure 6-4
4 Click the “ yes ” link to confirm the deletion, and wait for the confirmation message, shown in Figure 6 - 5