Databases Reference
In-Depth Information
This is a common problem in web applications, known as the reload problem ; it affects
not only writing to databases, but also tasks such as registering session variables,
charging credit cards, logging data, and every other situation in which an action has a
lasting effect. Fortunately, it's easy to avoid by not sending any content to the browser
from the script that actually performs the action, but to instead produce the output
from a different script.
Here's the previous script, rewritten to avoid the reload problem:
<?php
if(!empty($_GET))
{
// Include database parameters and related functions
require_once("../db.php");
$DB_databasename='music';
// Connect to the MySQL DBMS and use the wedding database
// - credentials are in the file db.php
if(!($connection= mysqli_connect($DB_hostname, $DB_username, $DB_password,
$DB_databasename)))
showerror($connection);
// Untaint the artist name, and use at most 15 characters
$artist_name = clean($_GET["artist_name"], 15);
// Add the artist, using the next available artist_id
$query="INSERT INTO artist (artist_id, artist_name) ".
"SELECT MAX(artist_id)+1, '$artist_name' FROM artist";
if (! @ mysqli_query($connection, $query))
die("Couldn't add artist");
// Silently send the browser to the receipt page
header("Location: receipt.php?Status=OK&artist_name=$artist_name");
}
else
{
print "No artist name was provided";
}
?>
This modified script adds the artist but doesn't produce HTML output. Instead, it sends
an HTTP header to the web browser using the PHP library header( ) function:
header("Location: receipt.php?Status=OK&artist_name=$artist_name");
The Location HTTP header instructs the web browser to go to another page, in this
case receipt.php . The receipt.php script performs no database activity, but simply
displays a confirmation message:
<?php
print "Added artist: ".$_GET['artist_name'];
?>
Figure 14-4 illustrates how the modified script works. Reloading this receipt page has
no effect on the database; users can reload it as many times as they wish.
 
Search WWH ::




Custom Search