9.2. Querying the Database with PHP FunctionsIn 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:
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 database9.2.1. Including Database Login DetailsYou'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.
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
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
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 filesExample 9-3 is an abbreviated dump of the database created from the mysqldump command. Example 9-3. The SQL to recreate the test objects
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 DatabaseThe 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
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.
Notice that we didn't specify the database name yet. 9.2.2.1. Troubleshooting connection errorsOne 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 DatabaseNow 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.
Now that you've got a good database connection, you're ready to execute your SQL query. 9.2.4. Building the SQL SELECT QueryBuilding 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.
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 QueryTo 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 DisplayingUse 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 typesThis 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 ConnectionAs 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 TogetherNow 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
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 browserIf 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
Example 9-6 displays in your browser as shown in Figure 9-4. Figure 9-4. The same data but in an HTML tableNotice 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. |