Databases Reference
In-Depth Information
"SELECT artist_id FROM artist WHERE
artist_name = \"{$_GET["artist"]}\"",
$connection)))
die("Couldn't find artist");
$row = @ mysql_fetch_array($result);
$artist_id = $row["artist_id"];
// Add the album, setting album_id to 1 and using the $artist_id
if (! @ mysql_query(
"INSERT INTO album (artist_id, album_id, album_name)
VALUES ({$artist_id}, 1, \"{$_GET["album"]}\")",
$connection))
die("Couldn't add album");
print "Added artist: {$_GET["artist"]}, with album: {$_GET["album"]}.";
?>
The script adds a new row to the
artist
table using an
INSERT ... SELECT
statement
and the
MAX( )
function described in Chapter 8. The
artist
value entered by the user
is stored in
$_GET["artist"]
. It then uses
SELECT
to find the
artist_id
of the newly
added row. The final step is to insert a row into the
album
table, using the new
artist_id
and the album name stored in
$_GET["album"]
, and setting the
album_id
to
1
(since this is the first album for the artist). Finally, the script displays a success message
or an error message depending on how things went.
The script has three serious problems. First, it's not secure: no steps are taken to ensure
that users pass sensible parameters to the script, and this can have serious consequences
for some scripts; we show you basic steps to guard against this next. Second, it suffers
from the
reload problem
that's discussed in “The Reload Problem,” later in this chapter.
When you request the
add.php
script a second time, it adds the same information to
the database again. Last, it doesn't have validation or error handling; for example, you
can insert the same artist more than once, each will be allocated a new
artist_id
, and
you won't see an error message. In Chapter 15, we'll look at examples of how to handle
such errors.
The PHP Predefined Superglobal Variables
Superglobal variables
are automatically created and initialized by the PHP engine, and
are accessible throughout the script. We've already seen the
$_GET
and
$_POST
associa-
tive arrays that contain data passed to the script from a form using the
GET
or
POST
method, respectively.
The array
$_SESSION
contains data related to a user's interaction with a web application
within a single session; we describe sessions and this variable in “Sessions,” later in this
chapter.