Form Elements: Letting the User Work with Data Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com... 149 Form Elements: Letting the User Work with Data Simpo PDF Me
Trang 1Figure 5-5
The SELECTelement (also known as list) allows you to display a fixed list of choices from which the userhas to choose an element The item selected won’t be sent as displayed but will be sent as its value Inthis example, the value and its display are identical, but in a database-driven system you would proba-bly see record IDs as the values and their text label as list choices A good example is a product numberand its name
When using lists, be sure to set the value part of the OPTIONitems If these are not set, the list looks thesame but is totally useless because all choices will send the same null value
One Form, Multiple Processing
Forms always react in a predefined way based on how you code your processing script to handle thedata that the user sends to the system A single form can have more than one defined action by using dif-ferent submit buttons
Trang 2Try It Out Radio Button, Multiline List Boxes
In the following example, you create a form that prepares a search and creates a movie/actor/directorinterface
1. Create a text file named form3.phpand open it in your text editor Then type the followingcode:
<form action=”formprocess3.php” method=”post”>
<table border=”0” cellspacing=”1” cellpadding=”3”
Form Elements: Letting the User Work with Data
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 3<input type=”checkbox” name=”Debug” checked>
</td>
</tr>
<tr>
<td bgcolor=”#FFFFFF” colspan=2 align=”center”>
<input type=”submit” name=”Submit” value=”Search”>
<input type=”submit” name=”Submit” value=”Add”>
You are <?php echo $_POST[‘Submit’]; ?>ing
<?php echo $_POST[‘Submit’] == “Search” ? “for “ : “”; ?>
a <?php echo $foo ?>
named “<?php echo $name; ?>”
</p>
Trang 43. Start your browser and open http://localhost/form3.php The form shown in Figure 5-6appears Notice that the form has two submit buttons One is labeled Search, the other Add
4. Type Kevin Kline in the Name field.
5. Leave Movie Typeas is; then move on to the Item Typefield, in which you’ll select Actor
6. Clear the Display Debug Dump checkbox if you like; then click the Search button The resultsappear, as shown in Figure 5-7
7. Now play around a bit with the form Look at the output and how it changes when you modifythe data
Form Elements: Letting the User Work with Data
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 5Figure 5-7
Radio INPUT Element
The radio button is a very simple element By default, if no radio button is specified as CHECKED, nodefault choice is made Always remember that choosing the default value is a very important part ofbuilding a form Users often leave defaults in forms (It is a form of laziness, so to speak.)
<input type=”radio” name=”type” value=”Movie” checked>
Trang 6Multiple Submit Buttons
As with radio buttons, submit buttons share the same name with a different value Clicking one of thesebuttons simply submits the form
<input type=”submit” name=”Submit” value=”Search”>
<input type=”submit” name=”Submit” value=”Add”>
As you can see in the DEBUGblock, the submit button sends its own information to the script You canaccess the submit button value through the $_POST[‘Submit’]array
Basic Input Testing
What about the processing script? What’s new in there?
The following code checks that the item type is Movie, and, if it is, it checks that the user has selected avalid movie type from the list If he or she has not, he or she is redirected to the form page
The test is a simple ifwith an andoperator (In simple Monopoly parlance, if the item type is movieand the movie type is not specified, you go back to square one and you do not collect $200.)
if ($_POST[‘type’] == “Movie” && $_POST[‘MovieType’] == “”) {header(“Location:form3.php”);
<?phpheader(“Location:form3.php”);
?>
This code will fail The empty line starting the script will send the headers with a carriage return and a line feed (depending on the operating system).
<?phpecho “foobar”;
header(“Location:form3.php”);
?>
This code will fail The echofunction will send the headers with the text “foobar”.
Dynamic Page Title
This code is rather simple to understand: You don’t start outputting as soon as you start executing thePHP script What often happens is that at the start of the scripts there will be a check for intrusion andcontext verification In this instance, you don’t have that sort of complex verification code, but you dodynamically set the page title using the action type and item type you will use to handle the page
149
Form Elements: Letting the User Work with Data
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 7<title><?php echo $title; ?></title>
Manipulating a String as an Array to Change
the Case of the First Character
Single string characters can be accessed through a very simple syntax that is similar to array index access.Specify the index of the character you want to access and voilà! To change the case of a character or anentire string, use the strtoupper()function:
$name = $_POST[‘Name’];
$name[0] = strtoupper( $name[0]);
You could have used the ucfirst()function (which essentially does what this code did), but a bit of creativity can’t hurt.
Ternary Operator
This line holds a ternary comparison operation Ternary operators are not PHP-specific; many other guages, such as C, use them
lan-<?php echo $_POST[‘Submit’] == “Search” ? “for “ : “”; ?>
These work in a very simple way and can be compared to an if-else structure:
[expression]?[execute if TRUE]: [execute if FALSE];
The ternary operator is a known maintainability hazard Using this operator will make your code less
readable and will probably cause errors during maintenance stages
Using Form Elements Together
Now that you know most of the form elements, let’s create a skeleton for the movie application The tem will add new items or search for existing ones Database interaction is covered in Chapter 6, how-ever, so for now you’ll just build the forms and echo the results to the screen
sys-Try It Out Bonding It All Together
In this exercise, you’ll create several new scripts that work together to simulate allowing the user to addinformation to the database
1. Create a file named form4.phpand open it in your text editor
Trang 8<?php// Debug info Displayfunction debugDisplay() {
?>
<pre>
$_POST
<?phpprint_r($_POST);
?>
$_GET
<?phpprint_r($_GET);
?>
</pre>
<?php}
if (!isset($_GET[‘step’])) {require(‘startform.php’);
case “1”:
$type = explode(“:”, $_POST[‘type’]);
if ($_POST[‘Submit’] == “Add”) {require($_POST[‘Submit’] $type[0] ‘.php’);
if ($_POST[‘Debug’] == “on”) {debugDisplay();
}break;
// #################
// Add Summary// #################
151
Form Elements: Letting the User Work with Data
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 9<form action=”form4.php?step=1” method=”post”>
<table border=”0” width=”750” cellspacing=”1” cellpadding=”3”
Trang 10<td bgcolor=”#FFFFFF” colspan=2 align=”center”>
<input type=”submit” name=”Submit” value=”Search”>
<input type=”submit” name=”Submit” value=”Add”>
Form Elements: Letting the User Work with Data
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 11<form action=”form4.php?step=2” method=”post”>
<input type=”hidden” name=”type” value=”<?php echo $type[1]; ?>”>
<input type=”hidden” name=”action”
value=”<?php echo $_POST[‘Submit’]; ?>”>
<table border=”0” width=”750” cellspacing=”1” cellpadding=”3”
<input type=”hidden” name=”type”
value=”Movie: <?php echo $_POST[‘MovieType’]; ?>”>
<td bgcolor=”#FFFFFF” colspan=”2” align=”center”>
<input type=”submit” name=”SUBMIT” value=”Add”>
Trang 125. Create a file named AddPerson.phpand enter the following code:
<form action=”form4.php?step=2” method=”post”>
<input type=”hidden” name=”type”
value=”Person: <?php echo $type[1]; ?>”>
<input type=”hidden” name=”action”
value=”<?php echo $_POST[‘Submit’]; ?>”>
<table border=”0” width=”750” cellspacing=”1” cellpadding=”3”
<td bgcolor=”#FFFFFF” colspan=”2” align=”center”>
<input type=”submit” name=”SUBMIT” value=”Add”>
155
Form Elements: Letting the User Work with Data
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 13Figure 5-8
7. Enter the name of the movie you want to add: “Grand Canyon.”
8. Click the Add button; this takes you to the add form shown in Figure 5-9
Trang 14Figure 5-9
9. Select a date for the year the movie was made (1991, if memory serves)
10. Select Drama in the Movie type list
11. Type a quick movie description, making sure you enter multiple lines, and press the Enter keybetween them
12. Click the Add button and see how the information is displayed (see Figure 5-10)
157
Form Elements: Letting the User Work with Data
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 15is maintainability It is a very common error that most people regret
Suppose that you have a site you made in the month after reading this book and you made a darn goodjob of it for a first site Six months later you’ve learned a lot and want to improve this site
At this very moment, the full force of chaos theory hits you square in the face: You can’t read yourcode anymore How unfortunate The goal now is to help you to separate things out in such a way that,when you come back to your code in six months, you won’t have to start from scratch (which, trust me,happens to most of us)
So, let’s get back to work How does this thing work, anyway? We discuss the elements you must decipher
Trang 16The Skeleton Script
The skeleton here is the form4.phpscript It all revolves around a use of the switch case structure Itstarts with a function definition for the debug display (which now holds the display of the $_GETsuperglobal array)
The trick resides in the fact that the forms will use the POSTmethods and thus transmit their informationthrough the $_POSTarray; the actual page content switching will be made through query strings passedthrough the $_GETarray
Each step in the building of the data is guided by the $_GET[‘step’]index value It holds the tion passed on by the ?step=1part of the URL
informa-Each value of the step GETparameter has a specific script attached to it This parameter tells the mainscript (index.php) where to branch to process the data received
Default Response
What happens when you call the page the first time and the step URL parameter is not set? Logicallyenough, the script evaluates the switchcondition and finds that it doesn’t match any of the specifiedcases, so it executes the default behavior:
switch ($_GET[‘step’]) {
inter-Adding Items
You need two different forms to add an item, depending on whether the user adds a person or a movie(at least if you consider that you store the same data in the database for the actors and directors) So youneed a second branching (the first branching being the step switch) to determine which form will be displayed
Now we hit a part of the script in which there is a little trick The list item value is used to store two ues instead of one The trick is to use a separator and then to explode the value into an array and accessthe piece you need (the explode()function takes each bit of text delimited by the separator and inserts
val-it as new array elements) Let’s take a closer look
In this case you have three types of items (Actors, Directors, and Movies), each of which requires a form
to create But you have decided that, so far, an Actor item and a Director item hold the same information
So you don’t need two different forms, just one You handle this by adding a tree structure level above
159
Form Elements: Letting the User Work with Data
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 17the item level, Person or Movie Under Person you include the Actor and Director level The whole point
is to be able to use the new hierarchy level name to name the file so that the including is automatic andyou can add new levels later without too much effort
In startform.phpyou have:
<input type=”radio” name=”type” value=”Person:Actor”>
For example, you have “Person:Actor”as the value to explode and a colon (:) as the delimiter Theresulting $typevariable will be an array holding the pieces of the string cut at each instance of the semi-colon If you represent it in the print_rformat, you have:
Array
(
[0] => Person[1] => Actor)
The goal of having simple filenames inclusion is achieved You have two Add scripts, and one name:AddPerson.phpand AddMovie.php
Trang 18spe-Forms are processed by the PHP script using the super global array $_GETand $_POST, which is a array of $_QUERY Each super global array has its use, as you saw, and contributes to making your scriptaccess the form data.
sub-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, # out of 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 selectfield on a subsequent page
3. Create a calculator form that takes two numbers and calculates their sum.
161
Form Elements: Letting the User Work with Data
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 20Most people use SQL to insert data that PHP modifies or generates You will try a slightly differentapproach and let SQL do its thing, data processing.
This chapter covers database editing, including:
❑ Adding entries, which is quite simple, but you will find that adding entries in a relationaldatabase 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
This may sound a bit Vulcan, but if you want to manage a database, the first logical thing to do is
to create one To save time, let’s use an existing database to avoid any problems in the comingexercises Create a new empty database in phpMyAdmin named moviesite.In the newborndatabase, execute the chapter6.mysqlscript (available at www.wrox.com), which holds thedatabase definition and its start data
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 21Try It Out Setting Up the Environment
First, you need a start page Follow these steps to create one:
1. Create a new directory called chap6under your htdocs (or create an alias, if you wish)
2. Create an index.phpscript and enter the following code:
<?php
$link = mysql_connect(“localhost”, “bp5am”, “bp5ampass”)
or die(“Could not connect: “ mysql_error());
<td bgcolor=”#FFFFFF” colspan=”2” align=”center”>
Movies <a href=”movie.php?action=add&id=”>[ADD]</a>
or die(“Invalid query: “ mysql_error());
while ($row = mysql_fetch_array($result)) {
<a href=”delete.php?type=movie&id=<?php echo $row[‘movie_id’]?>”>[DELETE]</a>
</td>
Trang 22<?php}
?>
<tr>
<td bgcolor=”#FFFFFF” colspan=”2” align=”center”>
People <a href=”people.php?action=add&id=”>[ADD]</a>
or die(“Invalid query: “ mysql_error());
while ($row = mysql_fetch_array($result)) {
<a href=”delete.php?type=people&id=<?php echo $row[‘people_id’]; ?>”>[DELETE]</a>
</td>
</tr>
<?php}
Letting the User Edit the Database
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 23Figure 6-1
How It Works
You must always have a central administration interface that allows you to perform actions on the dataand easily see the content This script is the admin interface It shows you everything and allows you tomanage everything in sight
What does it do and how does it do what it does? As in Chapter 4, where you connected to the databaseand displayed its contents, you will do the same thing here The table holds the name of each knownmovie and person, and generates EDIT and DELETE links
Inser ting a Simple Record from phpMyAdmin
Note that the following scripts follow a simple rule concerning SQL: Always try the query in MySQLbefore trying to insert it in your code The simple reason is that you are probably better off debuggingone language at a time
Trang 24Try It Out Inserting Simple Data
In this exercise, you’ll insert some data into your table
1. Open your database in phpMyAdmin or your favorite MySQL client, and enter the followingSQL code (yes, there is an error) as in Figure 6-2
INSERT INTO movie (movie_name, movie_type, movie_year)VALUES (‘Bruce Almighty’, ‘1’, ‘2003)
2. The following message appears (see Figure 6-3 for details):
You have an error in your SQL syntax Check the manual that corresponds to yourMySQL server version for the right syntax to use near ‘’2003)’ at line 2
Figure 6-2
167
Letting the User Edit the Database
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 26Figure 6-4
How It Works
When inserting a record in a table, you don’t need to insert the ID if you set the primary key field to autoincrement SQL will gladly handle that for you This enables you to be sure you don’t have duplicatekeys in the table
To get the just-inserted record’s auto increment id, just use the PHPmysql_insert_id()function rightafter the mysql_query()function call This function returns the primary key field when inserting a newrecord
You can find the mysql_insert_idfunction syntax on the PHP site at
www.php.net/mysql_insert_id.
169
Letting the User Edit the Database
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 27Because you have created the SQL query on more than one line, you can use the line number returned inthe following error message:
You have an error in your SQL syntax Check the manual that corresponds to yourMySQL server version for the right syntax to use near ‘’2003)’ at line 2
This line corresponds to the value part of your SQL statement, as shown here:
VALUES (‘Bruce Almighty’, ‘1’, ‘2003)
If your SQL query had been on one line, you’d have had only a useless “error in line 1” message Hereyou can see that on the guilty line you forgot to close a quote in the movie_yearvalue
Now you can see that we omitted the movie.movie_idfield We did this on purpose (yes, we did) Notspecifying the primary key value forces the MySQL engine to automatically determine the auto incrementvalue Thanks to this trick, you don’t need to know what the next key will be
Inser ting a Record in a Relational Database
Databases often hold more than just one table All those tables can be totally independent, but thatwould be like using your car to store some things in the trunk but never to drive you around
In old systems in which relational databases didn’t exist, every row held all the information Imagineyour system running with only one table holding all the information Your movietable would store allthe data about the actors and the directors and the movie types Suppose that one day you were todecide that a movie category should change from action to adventure (things change) You would thenhave to go through all records to change the movie type label
In modern RDBMS (relational database management systems), this is not the case anymore; you will ate a movietypetable storing a reference of all the possible movie types, and you will link movies to therelevant movie type
cre-To link those tables, you will use a primary key/foreign key team The primary key of the movietypetable is a numeric identification of each type of movie For example, in your database the id 1 referencescomedy The foreign key is the reference in the movietable to the movietypeprimary key
In the following exercise, you use PHP and SQL to insert a movie in your database This movie is of aknown movie type from the movietypereference table
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 whilespecifying an existing movie type and existing actor and director
1. Create a new empty file named movie.phpand enter the following code:
<?php
$link = mysql_connect(“localhost”, “bp5am”, “bp5ampass”)
Trang 28mysql_select_db(‘moviesite’, $link)
or die ( mysql_error());
$peoplesql = “SELECT * FROM people”;
$result = mysql_query($peoplesql)
or die(“Invalid query: “ mysql_error());
while ($row = mysql_fetch_array($result)) {
<form action=”commit.php?action=add&type=movie” method=”post”>
<table border=”0” width=”750” cellspacing=”1” cellpadding=”3”
$sql = “SELECT movietype_id, movietype_label “
“FROM movietype ORDER BY movietype_label”;
171
Letting the User Edit the Database
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 29<td bgcolor=”#FFFFFF” colspan=”2” align=”center”>
<input type=”submit” name=”SUBMIT” value=”Add”>
Trang 302. Save your file and upload it to the chapter6directory on your server.
3. Create a new empty file named commit.phpand enter the following code:
<?php// COMMIT ADD
$link = mysql_connect(“localhost”, “bp5am”, “bp5ampass”)
or die(“Could not connect: “ mysql_error());
mysql_select_db(‘moviesite’, $link)
or die ( mysql_error());
switch ($_GET[‘action’]) {case “add”:
switch ($_GET[‘type’]) {case “movie”:
$sql = “INSERT INTO movie
(movie_name,movie_year,movie_type,movie_leadactor,movie_director)VALUES
?>
4. Save your file and upload it to the chapter6directory on your server
173
Letting the User Edit the Database
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 315. Open your browser on the index.phppage and click ADD next to the movietable header.You should see the screen shown in Figure 6-5.
Figure 6-5
Trang 326. Add a movie named “Test” with random type, actor, and director as shown in Figure 6-6.
Figure 6-6
175
Letting the User Edit the Database
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 337. Click the “add” button and you will see the confirmation message as in Figure 6-7.
First, let’s concentrate on the people combos Each combo lists all persons present in a peopletable
<?php
$link = mysql_connect(“localhost”, “bp5am”, “bp5ampass”)
or die(“Could not connect: “ mysql_error());
mysql_select_db(‘moviesite’, $link)
or die ( mysql_error());
Trang 34$result = mysql_query($peoplesql)
or die(“Invalid query: “ mysql_error());
while ($row = mysql_fetch_array($result)) {
sys-<select name=”movie_director”>
<option value=”” selected>Select a director </option>
<?phpforeach ($people as $people_id => $people_fullname) {
?>
<option value=”<?php echo $people_id; ?>” ><?php echo $people_fullname; ?></option>
<?php}
?>
</select>
Here you’ve used the foreachsyntax to walk the array to generate all the options
Now generate the movie type combo box This is a more conventional use of SQL to generate contents.You’ll reuse this code soon to create a generic form to edit and add, so you need to understand thedetails of how this works
<select id=”game” name=”movie_type” style=”width:150px”>
<?php
$sql = “SELECT movietype_id, movietype_label “
“FROM movietype ORDER BY movietype_label”;
177
Letting the User Edit the Database
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 35Deleting a Record
Deleting records is easy (a bit too easy at times — you will know what we mean soon) As mentionedearlier, always be sure to test your queries on a test database Deleting records in a test database neverthreatens your system, and testing your query helps you find any SQL error before deleting all therecords in your production database because you forgot a little thing such as a WHEREclause MySQLdeletes everything that matches the SQL statement If you omit a WHEREclause in your query, all therecords will match the SQL statement, and thus will be deleted
Deleting always means losing data To delete a record you need to point the record to the databaseengine through a set of conditions in a WHEREstatement Once this statement is executed, there is noturning back The record(s) will be deleted without hope of return; that’s why we advise caution whenusing the DELETEstatement
Try It Out Deleting a Single Record
Before asking PHP to delete anything, you should try deleting a record from phpMyAdmin to ize yourself with the DELETEstatement
familiar-1. Open phpMyAdmin and enter the following code:
DELETE FROM movie
To avoid that problem, you can use a more elaborate form of the DELETEstatement, the Cascade Delete, as
discussed in the following section
Try It Out Cascade Delete
Now that you know how to use DELETE, you will add it to your system to delete a known person from thesystem As you store references to known people in the movietable, you will need to update the movietable content so you don’t reference deleted people (The update-specific exercises come next in this chap-ter.) 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 is left to a deleted record in the remaining data
Follow these steps to implement the Cascade Delete:
1. Create a new text file named delete.phpand enter the following code:
Trang 36$link = mysql_connect(“localhost”, “bp5am”, “bp5ampass”)
or die(“Could not connect: “ mysql_error());
if ($_GET[‘type’] == “people”) {// delete references to people from the movie table// delete reference to lead actor
$actor = “UPDATE movie
SET movie_leadactor = ‘0’
WHERE movie_leadactor = ‘“ $_GET[‘id’] “‘“;
$result = mysql_query($actor)
or die(“Invalid query: “ mysql_error());
// delete reference to director
$director = “UPDATE movie
$sql = “DELETE FROM “ $_GET[‘type’] “
WHERE “ $_GET[‘type’] “_id = ‘“ $_GET[‘id’] “‘
?>
2. Save delete.phpand upload it to your chap6 directory
179
Letting the User Edit the Database
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 373. Open index.phpin your browser You will see the DELETE links next to each movie or person
as in Figure 6-8
Figure 6-8
Trang 384. Try deleting the test movie you added in the previous exercise by clicking the DELETE link next
to the “Test” movie name You will be asked for confirmation as in Figure 6-9
Figure 6-9
181
Letting the User Edit the Database
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 395. Click the “yes” link to confirm the deletion and wait for the confirmation message as in
Carrey’s id will remain in the record and you will have a corrupted database You don’t want that, doyou? (The answer is no.)
Trang 40The solution to this problem is to make sure that you always have the round peg (a foreign key) in theround hole (a record) In the code that follows, you update the movietable with a 0 value (the defaultvalue telling the script you have not set the people part) before deleting the peoplerecord This alsoallows you to check the behavior of the UPDATESQL statement (Isn’t life great?)
// delete reference to lead actor
$actor = “UPDATE movie
SET movie_leadactor = ‘0’
WHERE movie_leadactor = ‘“ $_GET[‘id’] “‘“;
$result = mysql_query($actor)
or die(“Invalid query: “ mysql_error());
// delete reference to director
$director = “UPDATE movie
SET movie_director = ‘0’
WHERE movie_director = ‘“ $_GET[‘id’] “‘“;
$result = mysql_query($director)
or die(“Invalid query: “ mysql_error());
In the preceding code, you set any field in the movietable that might hold a reference to your nate, soon-to-be-deleted person The UPDATEstatement works in a very simple way It sets the fieldsspecified to the new value specified in all records, meeting the requirements of the WHEREstatement
unfortu-You might wonder what would happen if someone were to forget the WHEREpart Well, curiosity is a fine quality: This would update all records in the table, which is probably not something you want to do
in real life.
Once your tidying up is done, you do the deleting:
// generate SQL
$sql = “DELETE FROM “ $_GET[‘type’] “
WHERE “ $_GET[‘type’] “_id = ‘“ $_GET[‘id’] “‘
LIMIT 1”;
// echo SQL for debug purposeecho “<! ” $sql “ >”;
$result = mysql_query($sql)
or die(“Invalid query: “ mysql_error());
This DELETEquery is a bit dynamic, but it’s fairly understandable You don’t want to code a SQL ment for each type (Well, you did for the movies update, but it doesn’t count, does it?) So you use theinformation passed through the URL to generate your SQL statement The table and primary key fieldare generated dynamically from the item type to delete
state-Editing Data in a Record
Having data in the database is all well and good, but data has a mind of its own and tends to want to beupdated To update data, you need to identify the data to update and present the system user with a niceinterface to do so Using the same interface as was used to create the data is often a good practice
183
Letting the User Edit the Database
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com