Section 9.2. Querying the Database with PHP Functions


9.2. Querying the Database with PHP Functions

In this section, we introduce how to connect to a MySQL database with PHP. It's quite simple, and we'll begin shortly with examples, but we should talk briefly about what actually happens. When you try connecting to a MySQL database, the MySQL server authenticates you based on your username and password. PHP handles connecting to the database for you and allows you to immediately start performing queries and gathering data.

As in Chapter 8, we'll need the same pieces of information to connect to the database:

  • The IP address of the database server

  • The name of the database

  • The username

  • The password

If you're not sure what to use for these values, consult Chapter 7. And, before moving on, make sure you can log into your database using the mysql command-line client.

Figure 9-1 shows how the steps of the database interaction relate to the two types of resources. Building the SELECT statement happens before the third function call but is not shown. It's done with plain PHP code, not a MySQL-specific PHP function.

Figure 9-1. The interaction between functions and resources when using the database


9.2.1. Including Database Login Details

You're going to create a file to hold the information for logging into MySQL. Storing this information in a file you include is recommended. If you change the database password, there is only one place that you need to change it regardless of how many PHP files you have that access the database.

You don't have to worry about anyone directly viewing the file and getting your database login details. The file, if requested by itself, is processed as a PHP file and returns a blank page.


Let's call this file db_login.php and place it in the same directory as your other PHP files. The file is represented in Example 9-1.

Example 9-1. PHP file format

 <?php $db_host='hostname of database server'; $db_database='database name'; $db_username='username'; $db_password='password'; ?> 

In Example 9-2, we created this file to use a database on the same machine as the web server. We assign it a database name, username, and password.

Example 9-2. The db_login.php file with values filled in

 <?php $db_host='localhost'; $db_database='test'; $db_username='test'; $db_password='yourpass'; ?> 

Figure 9-2 illustrates how you're going to use this file with other PHP files. You're going to continue using the database that you started to set up in Chapter 7.

Figure 9-2. Reusing the login details in multiple files


Example 9-3 is an abbreviated dump of the database created from the mysqldump command.

Example 9-3. The SQL to recreate the test objects

 -- -- Table structure for table `authors` -- DROP TABLE IF EXISTS `authors`; CREATE TABLE `authors` (   `author_id` int(11) NOT NULL auto_increment,   `title_id` int(11) NOT NULL default '0',   `author` varchar(125) default NULL,   PRIMARY KEY  (`author_id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1; -- -- Dumping data for table `authors` -- INSERT INTO `authors` VALUES (1,1,'Ellen Siever'),(2,1,'Aaron Weber'),(3,2, 'Arnold Robbins'),(4,2,'Nelson H.F. Beebe'); -- -- Table structure for table `books` -- DROP TABLE IF EXISTS `books`; CREATE TABLE `books` (   `title_id` int(11) NOT NULL auto_increment,   `title` varchar(150) default NULL,   `pages` int(11) default NULL,   PRIMARY KEY  (`title_id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1; -- -- Dumping data for table `books` -- INSERT INTO `books` VALUES (1,'Linux in a Nutshell',476),(2,'Classic Shell Scripting',256); -- -- Table structure for table `purchases` -- DROP TABLE IF EXISTS `purchases`; CREATE TABLE `purchases` (   `id` int(11) NOT NULL auto_increment,   `user` varchar(10) default NULL,   `title` varchar(150) default NULL,   `day` date default NULL,   PRIMARY KEY  (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1; -- -- Dumping data for table `purchases` -- LOCK TABLES `purchases` WRITE; INSERT INTO `purchases` VALUES (1,'Mdavis','Regular Expression Pocket Reference', '2005-02-15'),(2,'Mdavis','JavaScript & DHTML Cookbook','2005-02-10'); 

If you didn't create the tables in the last chapter, the code in Example 9-3 can be saved as backup.sql and run from the command prompt with the following:

 mysql -u username -p password -D database_name < backupfile.sql 

The database is called test, and it consists of three tables called books, authors, and purchases. Each table has a few sample rows. That's enough to get us started querying from PHP.

9.2.2. Connecting to the Database

The first thing you need to do is connect to the database and check to make sure there's a connection. Including the file that you set up to store your connection information allows you to use the variables instead of hardcoded values when you call the mysql_connect function, as shown in Example 9-4.

Example 9-4. Including the connection values and calling mysql_connect

 <?php include('db_login.php'); $connection = mysql_connect($db_host, $db_username, $db_password); if (!$connection){ die ("Could not connect to the database: <br />". mysql_error()); } ?> 

The mysql_connect function takes the database host, username, and password as parameters. If the connection is successful, a link to a database is returned. FALSE is returned if a connection can't be made. Check the return value from the function to make sure there's a connection. If there's a problem, such as an incorrect password, print out a polite warning and the reason for the error using mysql_error.

Instead of simply echoing an error message, use the die function to display the error, and then stop the program, Not being able to access the database makes most database-driven pages fairly useless and prevents the user from seeing numerous errors.


Notice that we didn't specify the database name yet.

9.2.2.1. Troubleshooting connection errors

One error you may get is:

 Fatal error: Call to undefined function mysql_connect() in C:\Program Files\Apache Group\Apache2\htdocs\test.php on line 4 

This occurs because PHP 5.1.2 for Windows was downloaded, and MySQL support was not included by default. To fix this error, copy the php_mysql.dll file from the ext/ directory of the PHP zip file to C:\php, and then edit lines 461 and 589 of C:\WINDOWS\php.ini. This will change the extension to include the directory to C:/php and uncommenting the MySQL extension line, respectively.

You'll need to restart Apache, and then MySQL support will be enabled.

9.2.3. Selecting the Database

Now that you're connected, the next step is to select which database to use with the mysql_select_db command. It takes two parameters: the database name and, optionally, the database connection. If you don't specify the database connection, the default is the connection from the last mysql_connect.

 $db_select = mysql_select_db($db_database); if (!$db_select){ die ("Could not select the database: <br />". mysql_error()); } 

Again, it's good practice to check for an error and display it every time you access the database.

While it's possible to call mysql_select_db multiple times within the same script, it's not considered good practice. Generally, you should be able to do all of your work with one database. Maintaining connections and results to multiple databases are beyond this book's scope.


Now that you've got a good database connection, you're ready to execute your SQL query.

9.2.4. Building the SQL SELECT Query

Building a SQL query is as easy as setting a variable to the string that is your SQL query. Of course, you'll need to use a valid SQL query, or MySQL returns with an error when you execute the query. The variable name $query is used, but you can choose anything you'd like for a variable name. The SQL query in this example is SELECT * FROM books.

Unlike when you used the mysql command-line client, the query does not have a semicolon at the end.


You can build up your query in parts using the string concatenate (.) operator:

 $select = ' SELECT '; $column = ' * '; $from = ' FROM '; $tables = ' `books` '; $where = ''; $query = $select.$column.$from.$tables.$where; 

Which is a more flexible version of this:

 $query = "SELECT * FROM books"; 

The query string could also use a variable in the WHERE clause to limit which rows are returned based on user information or another query.

Now that you have your query assigned to a variable, you can execute it.

9.2.5. Executing the Query

To have the database execute the query, use the mysql_query function. It takes two parametersthe query and optionally the database linkand returns the result. Save a link to the results in a variable called, you guessed it, $result! This is also a good place to check the return code from mysql_query to make sure that there were no errors in the query string or the database connection by verifying that $result is not FALSE.

 $result = mysql_query( $query ); if (!$result) { die ("Could not query the database: <br />". mysql_error()); } 

When the database executes the query, all of the results form a result set. These correspond to the rows that you saw upon doing a query using the mysql command-line client. To display them, you process each row, one at a time.

9.2.6. Fetching and Displaying

Use mysql_fetch_row to get the rows from the result set. It takes the result you stored in $result from the query as a parameter. It returns one row at a time from the query until there are no more rows, and then it returns FALSE. Therefore, you do a loop on the result of mysql_fetch_row and define some code to display each row:

 while ($result_row = mysql_fetch_row($result)){        echo $result_row[2] . '<br />'; } 

9.2.6.1. Fetch types

This is not the only way to fetch the results. Using mysql_fetch_array, PHP can place the results into an array in one step. It takes a result as its first parameter, and the way to bind the results as an optional second parameter. If MYSQL_ASSOC is specified, the results are indexed in an array based on their column names in the query. If MYSQL_NUM is specified, then the number starting at zero accesses the results. The default value, MYSQL_BOTH, returns a result array with both types. The mysql_fetch_assoc is an alternative to supplying the MYSQL_ASSOC argument.

If you rewrote the code above to use mysql_fetch_array with an associative indexed array, it would look like this:

 while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {                                 echo $row[title]. '<br />'; } 

9.2.7. Closing the Connection

As a rule of thumb, you always want to close a connection to a database when you're done using it. Closing a database with mysql_close will tell PHP and MySQL that you no longer will be using the connection, and will free any resources and memory allocated to it.

 mysql_close($connection) 

9.2.8. Putting It All Together

Now you're going to take all of the steps and put them into a single PHP file that you'll call db_test.php. You should place the PHP script shown in Example 9-5 in the same directory as the db_login.php file.

Example 9-5. Displaying the books and authors

 <?php // Include our login information include('db_login.php'); // 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 $db_select=mysql_select_db($db_database); if (!$db_select) {    die ("Could not select the database: <br />". mysql_error()); } // Assign the query $query = "SELECT * FROM `books` NATURAL JOIN `authors`"; // Execute the query $result = mysql_query( $query ); if (!$result) {    die ("Could not query the database: <br />". mysql_error()); } // Fetch and display the results while ($result_row = mysql_fetch_row(($result))) {        echo 'Title: '.$result_row[1] . '<br />';        echo 'Author: '.$result_row[4] . '<br /> ';        echo 'Pages: '.$result_row[2] . '<br /><br />'; } / /Close the connection mysql_close($connection); ?> 

Here's the output from Example 9-5:

 Title: Linux in a Nutshell<br />Author: Ellen Siever<br /> Pages: 476<br /> <br />Title: Linux in a Nutshell<br />Author: Aaron Weber<br /> Pages: 476<br /> <br />Title: Classic Shell Scripting<br>Author: Arnold Robbins<br /> Pages: 256<br /> <br />Title: Classic Shell Scripting<br />Author: Nelson H.F. Beebe<br /> Pages: 256<br /><br /> 

This displays in your browser as in Figure 9-3.

Figure 9-3. How Example 9-5 displays in the browser


If you don't see the screen in Figure 9-3, then you'll see an error from whichever step in the process had a problem, giving you an idea of what went wrong and where it was wrong.

To make the display more appealing, you can put the information into a table, as shown in Example 9-6. You also add complete HTML headers.

Example 9-6. Displaying the results of a query in an HTML table

 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html401/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <title>Displaying in an HTML table</title> </head> <body> <table border="1"> <tr> <th>Title</th> <th>Author</th> <th>Pages</th> </tr> <?php //Include our login information include('db_login.php'); // 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 $db_select = mysql_select_db($db_database); if (!$db_select){ die ("Could not select the database: <br />". mysql_error()); } // Assign the query $query = "SELECT * FROM `books` NATURAL JOIN `authors`"; // Execute the query $result = mysql_query($query); if (!$result){ die ("Could not query the database: <br />". mysql_error()); } // Fetch and display the results while ($row = mysql_fetch_array($result, MYSQL_ASSOC)){ $title = $row["title"]; $author = $row["author"]; $pages = $row["pages"]; echo "<tr>"; echo "<td>$title</td>"; echo "<td>$author</td>"; echo "<td>$pages</td>"; echo "</tr>"; } // Close the connection mysql_close($connection); ?> </table> </body> </html> 

Example 9-6 displays in your browser as shown in Figure 9-4.

Figure 9-4. The same data but in an HTML table


Notice that you made use of the MYSQL_ASSOC fetch type in Example 9-6. You're probably saying to yourself, "That's great, but how do I display the book titles with the authors all on one line?" This is where we talk about PEAR.



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