Retrieving Data
Next you create a directory for the application. A good place for this would be /opt/apache/htdocs/addressbook for an Apache installation, /opt/apache or C:\INETPUB\WWWROOT\ADDRESSBOOK for IIS. The default page for the application will be index.php3; you must configure your Web server to recognize index.php3 as the default page for a directory.
Listing 4 shows the code for index.php3, a script that generates an index page of all entries in the database sorted by last name. Each displayed name serves as a link to a page that allows users to view all fields for the selected name.
Listing 4. PHP script indexes entries by last name
|
In Listing 4 (and in the other listings below), you replace mylogin and mypasswd with the correct login and password for your MySQL database. The first PHP command in Listing 4 is mysql_pconnect on line 8, which establishes a database connection. There is also a mysql_connect function available. The mysql_pconnect command opens a persistent database connection that remains open after the page finishes processing. The subsequent request reuses the connection to improve performance.
Opening a database connection often is the slowest step in a Web application. Connections opened with mysql_connect automatically close after the page finishes processing.
Line 11 of Listing 4 submits to the database an SQL query that asks for all address book entries sorted by last name. A simple while loop, in conjunction with mysql_fetch_array, retrieves each of the entries. The C-style printf statement formats the output for each entry as a link to view the entry. The ID column of each entry serves as a parameter of the URL.
The $res result set variable returned from mysql_fetch_array is an associative array. The values for each table column (LAST_NAME, FIRST_NAME, etc.) are accessed using the name of the column.
Line 18 of Listing 4 frees the resources for the result set. You need not explicitly free the result set, because PHP does that for you automatically after the page is processed, but it's typically recommended. In some applications, you issue a large number of queries that could use up significant system resources if not they are not freed during execution. (Note: PHP 4.0 automatically frees resources as they are dereferenced.)
View Script Web databases quickly with PHP Discussion
Page: 1 2 3 4 5 6 7 8 Next Page: Form Processing