The database connection requires two steps when you are not using PEAR. First, you must connect to the database. Once you have connected, the survey database is selected.
<?php //set the connection details $db_host='localhost'; $db_database='test'; $db_username='test'; $db_password='yourpass'; //call mysql_connect to connect $connection = mysql_connect($db_host, $db_username, $db_password); if (!$connection){ die ("Could not connect to the database: <br />". mysql_error()); } //select the database using mysql_select_db $db_select = mysql_select_db($db_database); if (!$db_select){ die ("Could not select the database: <br />". mysql_error()); } ?>
Solution to Question 9-3
Add the following to the end of the code from Solution 9-2:
<?php $query = "SELECT * FROM authors"; $result = mysql_query( $query ); if (!$result) { die ("Could not query the database: <br />". mysql_error()); } while ($result_row = mysql_fetch_row(($result))) { echo 'Author ID: '.$result_row[0] . '<br />'; echo 'Title ID: '.$result_row[1] . '<br /> '; echo 'Author Name: '.$result_row[2] . '<br /><br />'; } //Close the connection mysql_close($connection); ?>
Solution to Question 9-4
The PEAR functions are more compact, and they automate some of the manual work of connecting to and selecting from the database. Because PEAR code is used by many developers, it is less likely to have an error than to have code that's written from scratch.