- Advanced Database Interaction in PHP4
- Database-Specific Functions in PHP
- DBX—PHP Support for Multiple Databases
- Creating Your Own Support for Multiple Databases
- Using Pear::DB
DBXPHP Support for Multiple Databases
For applications that don't require complex database-specific queries, you can use PHP's built-in DBX functions.
Before you can use the DBX functions, you must enable support at compile time if you are using Linux or enable the DBX module if you are using Windows.
Enabling DBX in Linux
If you compiled PHP using Apache's APXS functionality (compile --with-apxs=/path/to/apache/bin/apxs), then adding functionality to the PHP module is a breeze.
Before recompiling PHP, I first suggest that you delete the config.cache file and clean up files left over from the previous compile. This can be done like this:
cd /path/to/php/source rm config.cache make clean
After you issue the make clean command, you will notice quite a few files being deleted. Don't worry about it. The make program is just cleaning up files it won't need when you recompile. If you don't run the make clean command, then you may start running into some problems. If you have been compiling PHP with no problems and suddenly it won't compile right, even though you haven't changed anything, it's a good bet that the make clean command will solve your problem.
Once you've cleaned up the mess from the previous compile, you can get started with the new compile.
To compile PHP with DBX support enabled, issue the following command from a shell prompt (replacing paths specific to your install as necessary):
./compile --with-apxs=/usr/local/apache/bin/apxs --enable-dbx \
You should also enable support for any database that you wish to use as wellfor example:
--with-mssql
After the configure runs, issue the command:
make
Assuming no errors occur, you can then issue the command:
make install
The final command copies the libphp4.so library file to /path/to/apache/libexec/.
Restart Apache to load the new library:
/path/to/apache/bin/apachectl restart
You can verify that DBX has been correctly installed by using the phpinfo() function and verifying that DBX is listed under the configuration section.
Enabling DBX in Windows
Enabling DBX support for Windows is very easy, since the DLL file for DBX has been precompiled and included in the basic PHP windows installation. Open your php.ini file in a text editor and search for the line that says:
extension_dir = ./
This line should point to the place where your PHP extensions reside. If you copied the extensions to the same directory as the php.ini file, then you do not need to modify the line. If you did not move the PHP extensions to the same directory as the php.ini file, then you need to edit the line to point to the correct directory, for example:
extension_dir = C:\Apache\php\extensions
Next, find the section in the php.ini file that says:
;Windows Extensions
This line will be followed by many lines of windows .dll extensions for php. To enable DBX support, uncomment (delete the semicolon at the beginning of the line) the line that contains the DBX library DLL:
extension=php_dbx.dll
After you have uncommented the line, save the file and restart the Apache Web server.
You can verify that DBX has been correctly installed by using the phpinfo() function and verifying that DBX is listed under the configuration section.
DBX Functions
The DBX functions are a single set of functions that allows you to access multiple supported databases without having to write your own wrapper functions.
As of version 4.1, PHP DBX supports the following databases:
- mysql
- odbc
- pgsql
- mssql
- fbsql
The following functions are available in DBX:
DBX_CLOSE(CONNECTION)
The dbx_close() function takes one argument, CONNECTION. CONNECTION is the link identifier created when you call the dbx_connect() function.
DBX_CONNECT(MODULE, HOST, DATABASE, USER, PASSWORD, PERSISTENT)
The dbx_connect() function is used to establish a connection to the database server, as well as specify which database is to be used. dbx_connect returns an object that contains the handle of the connection as well as the name of the database to which it is connected. See the example for details. The dbx_connect function accepts six arguments:
MODULEThe database module that you want to use for this connection. The module is essentially the database type to which you are trying to connect. Values may be:
DBX_MYSQLFor MySQL databases.
DBX_ODBCFor any database which supports an ODBC connection.
DBX_PGSQLFor PostgreSQL databases.
DBX_MSSQLFor MS SQL databases.
DBX_FBSQLFor Frontbase database.
HOSTThe host name or IP address of the database server.
DATABASEThe name of the database on the database server.
USERThe username.
PASSWORDThe password for the user.
PERSISTENTWhether or not to make this a persistent connection. If you wish to make the connection persistent, then put DBX_PERSISTENT here. Otherwise, this argument is not required.
Example:
$module = DBX_MYSQL; //note the absence of quotes! $dbconn = dbx_connect($module, "192.168.0.5", "php", "mysqluser", "password")
or DIE ("Unable To Connect"); //$dbconn->database = "php" //$dbconn->handle is a resource identifer
DBX_ERROR(CONNECTION)
The dbx_error function returns the error from the latest function call to the module. The argument CONNECTION is the link identifier defined when you called dbx_connect().
Example:
$result = dbx_query($dbconn, "select something from non_existing_table"); if ($result == 0) {echo dbx_error($dbconn); } //responds: Table 'php.non_existing_table' doesn't exist
DBX_QUERY(CONNECTION, SQL STATEMENT, FLAGS)
The dbx_query function lets you send SQL queries to the database. It returns an object if the query does not fail and the query returns one or more rows. A query that returns zero rows does not return an object. Instead it returns 1, for the query was successful, but there was no data returned, such as when you select * from a table that has no data. The arguments are:
CONNECTIONThe link identifier created when you call the dbx_connect() function.
SQL STATEMENTA standard SQL statement.
FLAGSYou can specify how much information is returned by the query by specifying one or more of the following flags. By default, all flags are turned on. When specifying the flags, you must use a | symbol to separate themfor example "DBX_RESULT_INDEX | DBX_RESULT_INFO". The flags are:
DBX_RESULT_INDEXAlways returned. All results in the result array are indexed by a number, i.e., $result[0], $result[1], etc.
DBX_RESULT_INFOReturns information about the columns returned, such as field name and field type.
DBX_RESULT_ASSOCSets the keys of the returned array to the column names.
The object returned by dbx_query contains the following properties:
handleThe same handle that is available from $dbconn->handle. Accessed as $result->handle.
colsThe number of columns in the result set. Accessed by $result->col.
rowsThe number of rows in the result set. Accessed by $result->rows.
infoReturned only if either DBX_RESULT_INFO or DBX_RESULT_ASSOC is specified in the flag's parameter. Provides a two-dimensional array containing the name of the column and its type. Accessed by $result['info'][$x] and $result['name'][$x], where $x is the index of the particular row.
dataContains the actual data from result. Accessed by $result->data[$x]['field name'] where $x is the index of the particular row.
Example:
$result = dbx_query($dbconn, "select something from some_table", DBX_RESULT_INFO);
DBX_SORT(RESULT, SORT FUNCTION)
The dbx_sort function allows you to sort the results of a query using your own custom sort function. However, it is more efficient to use the "ORDER BY" clause in your SQL statement. The arguments the dbx_sort accepts are:
RESULTThe result of a previous dbx_query statement.
SORT FUNCTIONYour custom sort function.
Example:
function my_sort { //your custom sort definition } dbx_sort($result, "my_sort"); //$result is now sorted according to my_sort()
DBX_COMPARE(ROW1, ROW2, COLUMN KEY, FLAGS)
The dbx_compare function allows you to compare two result sets, ROW1 and ROW2. If ROW1 = ROW2, then dbx_compare returns 0. If ROW1 > ROW2, then dbx_compare returns 1. If ROW1 < ROW2, then dbx_compare returns 1. The arguments that dbx_compare accepts are:
ROW1A result from a dbx_query function call.
ROW2A result from a dbx_query function call.
COLUMN KEYThe name of the column on which the comparison should be made.
FLAGSYou can specify several flags to compare the rows in ascending or descending order, and what type of comparison should be made. Separate the order of any type by a pipe.
DBX_CMP_ASC(default) Compare in ascending order.
DBX_CMP_DESCCompare in descending order.
DBX_CMP_NATIVE(default) Compare the items "as is."
DBX_CMP_TEXTCompare the items as strings.
DBX_CMP_NUMBERCompare the items as numbers.
Example:
$comp = dbx_compare ($r1, $r2, "income"); //$comp = 0 if $r1 = $r2 //$comp = 1 if $r1 > $r2 //$comp = -1 if $r < $r2
Using DBX
Now that you have some idea of how the DBX functions work, let's create a small URL database to keep track of some of your favorite links. Since you are using DBX, you can use this application with any database that is supported by DBX. Figure 31 shows dbx_urls.php in action.
FIGURE 31 dbx_urls.php
Script 31 dbx_urls.php Script 38
1. <html> 2. <head> 3. <title>A PHP-DBX URL Organizer</title> 4. <style type=text/css> 5. p, ul, td, h1, h2, h3 {font-family: verdana, helvetica, sans-serif;} 6. </style> 7. </head> 8. <body> 9. <? 10. /***** 11. * TABLE DEFINITION FOR THIS EXAMPLE: 12. * create table URLS ( 13. * url VARCHAR(128) not null, 14. * description TEXT, 15. * primary key (url)); 16. *****/ 17. //define $MODULE as DBX_MYSQL, DBX_MSSQL, DBX_PGSQL, or your supported database 18. $MODULE = DBX_PGSQL; 19. $server = "192.168.0.5"; 20. $user = "psqluser"; 21. $password = "password"; 22. $database = "php"; 23. /* FUNCTIONS */ 24. function get_urls($dbconn, $sql) { 25. $result = @dbx_query($dbconn, $sql); 26. if ( $result == 0 ) { 27. echo dbx_error($dbconn); 28. } else { 29. return $result; 30. } 31. } 32. function url($action, $dbconn, $url, $description) { 33. if($action == "add") { 34. $sql = "insert into URLS values('$url', '$description')"; 35. }elseif($action == "delete") { 36. $url = urldecode($url); 37. $sql = "delete from URLS where URL = '$url'"; 38. } 39. $result = @dbx_query($dbconn, $sql); 40. if ( $result == 0 ) { 41. echo "<P>ERROR ADDING URL: " . dbx_error($dbconn); 42. } else { 43. print("<p>$action : $url succeeded!<p>"); 44. } 45. } 46. /*** MAIN ***/ 47. $dbconn = dbx_connect($MODULE, $server, $database, $user, $password) or die("CANNOT CONNECT TO DATABASE"); 48. ?> 49. <h1>PHP DBX URL Organizer</h1> 50. <form action=dbx_urls.php method=post> 51. <p><b>Add a URL:</b> 52. <br>URL: <input type="text" name="url" maxlength="128" value="http://"> Description: <input type="text" name="description"> <input type="submit" name="addurl" value="Add URL!"> 53. </form> 54. <? 55. if(isset($addurl)) { 56. url("add", $dbconn, $url, $description); 57. } 58. if(isset($delete)) { 59. url("delete", $dbconn, $delete, ""); 60. } 61. $sql = "select * from URLS"; 62. $result = get_urls($dbconn, $sql); 63. if(sizeof($result->data) == 0) { 64. ?> 65. <h3>Sorry, there are no URLs in the database. You should add some. 66. <? 67. } else { 68. ?> 69. <p> 70. <table border=1 cellpadding=5 cellspacing=0 width=600> 71. <tr><td><b>URL</b></td><td> <b>Description</b></td><td> </td></tr> 72. <? 73. for($i = 0; $i < sizeof($result->data); $i++) { 74. ?> 75. <tr><td><a href=<?=$result->data[$i]['url']?>><?=$result->data[$i] ['url']?></a></td> 76. <td><?=$result->data[$i]['description']?></td> 77. <td width=1><a href=dbx_urls.php?delete=<?=urlencode($result->data[$i] ['url'])?>>delete</a></tr> 78. <? 79. } 80. ?></table><? 81. } 82. ?> 83. </body> 84. </html>
Script 31 dbx_urls.php Line-by-Line Explanation
LINE |
DESCRIPTION |
18 |
Print out normal HTML to start the page. |
1016 |
The SQL statement required to create the table for this example. |
18 |
The $MODULE definition for the type of database the script will access. Valid choices are defined in line 17. |
19 |
Define the database server host name or IP. |
20 |
Define the database user's username. |
21 |
Define the database user's password. |
22 |
Define the database name on the database server. |
24 |
Define a function to query the database and return the URLs in the database. |
25 |
Issue the query. Note the "@" sign before the call to the dbx_query() function. The "@" sign suppresses any warning that may be issued if something goes awry with the functionfor example, if the database is down. More information on handling these errors is available in Chapter 8. |
26 |
If the $result == 0, then there was an error, because upon success, the dbx_query is supposed to return an object. |
27 |
Print out the error if line 26 is true. |
2830 |
If there was no error, then return the result object. |
30 |
End the function declaration. |
32 |
Define a function to add or remove URLs from the database called url(). The function takes the following arguments: $actioneither "add" or "delete" $dbconnthe connection link to the database $urlthe URL to be added or removed $descriptionthe description of the URL |
33 |
If the $action argument is "add", then we are adding a URL. |
34 |
Generate the SQL to add the URL. |
35 |
If $action is not "add", then check to see if it is "delete". |
36 |
Decode the encoded URL. |
37 |
Generate the SQL to delete the URL. |
38 |
End the if/else statement started on line 33. |
39 |
Query the database with the generated SQL. |
40 |
If the $result == 0, then there was an error, because upon success, the dbx_query is supposed to return an object. |
41 |
Display an error to the user including the specific DBX error message. |
4244 |
If there wasn't an error querying the database, then display a success message to the user. |
45 |
End the function. |
46 |
Start the man program. |
47 |
Generate the database connection string with the variables defined at the beginning of the script. |
4953 |
Print out the HTML for the page that displays the heading, as well as the form to add URLs. |
5557 |
If the "Add URL!" button has been pushed, then run the url() function. |
5860 |
If a "Delete" link has been clicked next to any of the URLs, then run the url() function. |
61 |
Generate an SQL statement to retrieve the URLs. |
62 |
Run the get_url() function using the SQL generated above to retrieve the URLs from the database. |
63 |
Check to make sure there was data in the result set that was returned from the get_urls() function. If there was no data, then the database is empty. |
65 |
Display a message to the user that the database was empty. |
67 |
If the database was not empty, then execute the rest of the script. |
7071 |
Create a table to display the URLs. |
73 |
Start a for loop to loop through the data returned from the get_url() function. |
75 |
Print out the URL to the table and include a hyperlink to the URL. |
76 |
Print out the description of the URL to the table. |
77 |
Print a delete link for the URL. |
79 |
End the for loop. |
81 |
End the if/else statement started on line 63. |
8384 |
Close out the HTML for the page. |