Databases Reference
In-Depth Information
be tempted to use the constants FALSE and TRUE here; this doesn't solve the problem,
however, since there's no clear connection between either of these values and the re-
served or unreserved status of a gift.
One useful technique in writing code that is self-documenting —that is, code that is easy
to read and understand on its own—is to define and use constants that have meaningful
names. For example, instead of 0 and 1 , we can use SHOW_UNRESERVED_GIFTS and
SHOW_GIFTS_RESERVED_BY_THIS_USER . In “Handling errors in production code” in Chap-
ter 14, we used the define( ) function to store the administrator's email address in a
constant. We can also use this function to define the two constants we need here:
define("SHOW_UNRESERVED_GIFTS", 0);
define("SHOW_GIFTS_RESERVED_BY_THIS_USER", 1);
To show the gifts that are unreserved, and then the gifts that have been reserved by the
current user, we call the function once with the last parameter set to SHOW_UNRE
SERVED_GIFTS , and once with it set to SHOW_GIFTS_RESERVED_BY_THIS_USER .
The function itself first tests whether there are any gifts in the database and displays an
error message if there aren't any:
// Show the user the gifts
//
// Parameters:
// (1) An open connection to the DBMS
// (2) Whether to show the available gifts or the current user's
// shopping list.
// Define constants for use when calling showgifts
define("SHOW_GIFTS_RESERVED_BY_THIS_USER", TRUE);
define("SHOW_UNRESERVED_GIFTS", FALSE);
function showgifts($connection, $show_user_selection)
{
// See whether there are any gifts in the system
$query = "SELECT * FROM gifts";
// Run the query through the connection
if (($result = @ mysqli_query($connection, $query))==FALSE)
showerror($connection);
// Check whether any gifts were found
if (@ mysqli_num_rows($result) == 0)
// No; print a notice
echo "\n<h3><font color=\"red\">".
"There are no gifts described in the system!</font></h3>";
else
{
// Yes; display the gifts
}
}
 
Search WWH ::




Custom Search