Databases Reference
In-Depth Information
Removing a Gift
If the requested action is not add , it can only be remove , since only these two values are
accepted for further processing by our script. The script checks that the gift is actually
reserved by the current guest before freeing it; this check should never fail in practice,
unless the same user is logged in twice. This is another example of defensive
programming.
As with the add operation, we prepare a message confirming that the gift has been
removed if the number of affected rows is one, and an error message if it isn't:
// Create a query to retrieve the gift.
$query = "SELECT * FROM gifts WHERE gift_id = {$gift_id}";
// Run the query through the connection
if (($result = @ mysqli_query($connection, $query))==FALSE)
showerror($connection);
// Get the matching gift row;
// (there's only one since the gift_id is the primary key)
// If we don't get exactly one answer, then we have a problem
for($matchedrows=0;($row = @ mysqli_fetch_array($result));$matchedrows++);
if($matchedrows!=1)
die("We've just experienced a technical problem - ".
"please notify the administrator.");
// Double-check they actually have this gift reserved
if (!empty($row["username"]) && $row["username"] != $_SESSION['username'])
// They don't, so record a message to show the user
$message = "That's not your gift, {$_SESSION['username']}!";
else
{
// They do have it reserved. Create a query to unreserve it.
$query = "UPDATE gifts SET username = NULL WHERE gift_id = {$gift_id}";
// Run the query through the connection
if (($result = @ mysqli_query($connection, $query))==FALSE)
showerror($connection);
// Create a message to show the user
if (mysqli_affected_rows($connection) == 1)
$message = "Removed the gift from your shopping list, ".
"{$_SESSION['username']}";
else
$message = "There was a problem updating. ".
"Please contact the administrator.";
}
An alternative approach would be to include a check for the username in the UPDATE
statement, and to execute this statement first. We could then determine whether the
gift was in fact reserved by this user by counting the number of affected rows:
// Try to unreserve the gift with the matching username and gift ID
$query = "UPDATE gifts SET username = NULL WHERE gift_id = {$gift_id}".
 
Search WWH ::




Custom Search