O'Reilly logo

Managing & Using MySQL, 2nd Edition by Hugh E. Williams, Randy Yarger, George Reese, Tim King

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required