Section A.9. Chapter 9


A.9. Chapter 9


Solution to Question 9-1

The database connection string is formatted as follows:

 mysql://db_username:db_password@db_host/db_database: mysql://joe:my$ql@oreilly.com/survey 


Solution to Question 9-2

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.



Learning PHP and MySQL
Learning PHP and MySQL
ISBN: 0596101104
EAN: 2147483647
Year: N/A
Pages: 135

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net