Opening and Using a Database Connection

Several PHP library functions are used to connect to a MySQL DBMS, run queries, retrieve results, and handle any errors that occur along the way. The presents.php script shown in Example 11-2 illustrates five of these functions in action.

Example 11-2. Querying a MySQL DBMS using PHP to display the gift registry
<?php // Show the user the available presents and the presents in their shopping // list // Include the DBMS credentials include 'db.inc'; // Check if the user is logged in // (this also starts the session) logincheck( ); // Show the user the gifts // // Parameters: // (1) An open $connection to the DBMS // (2) Whether to show the available gifts with the option to add // them to the shopping list ($delete = false) or to show the current // user's shopping list with the option to remove the gifts ($delete = true) // (3) The $user name function showgifts($connection, $delete, $user) { // If we're showing the available gifts, then set up // a query to show all unreserved gifts (where people IS NULL) if ($delete == false) $query = "SELECT * FROM presents WHERE people_id IS NULL ORDER BY present"; else // Otherwise, set up a query to show all gifts reserved by // this user $query = "SELECT * FROM presents WHERE people_id = \"{$user}\" ORDER BY present"; // Run the query if (!($result = @ mysql_query ($query, $connection))) showerror( ); // Did we get back any rows? if (@ mysql_num_rows($result) != 0) { // Yes, so show the gifts as a ...

Get Managing & Using MySQL, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.