Home > Articles > Programming > PHP

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

DBX—PHP 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 well—for example:


After the configure runs, issue the command:


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:


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:


The dbx_close() function takes one argument, CONNECTION. CONNECTION is the link identifier created when you call the dbx_connect() function.


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:

  • MODULE—The 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_MYSQL—For MySQL databases.

  • DBX_ODBC—For any database which supports an ODBC connection.

  • DBX_PGSQL—For PostgreSQL databases.

  • DBX_MSSQL—For MS SQL databases.

  • DBX_FBSQL—For Frontbase database.

  • HOST—The host name or IP address of the database server.

  • DATABASE—The name of the database on the database server.

  • USER—The username.

  • PASSWORD—The password for the user.

  • PERSISTENT—Whether 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.


$module = DBX_MYSQL; //note the absence of quotes!
$dbconn = dbx_connect($module, "", "php", "mysqluser", "password") 
or DIE ("Unable To Connect"); //$dbconn->database = "php" //$dbconn->handle is a resource identifer


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().


$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 


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:

  • CONNECTION—The link identifier created when you call the dbx_connect() function.

  • SQL STATEMENT—A standard SQL statement.

  • FLAGS—You 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 them—for example "DBX_RESULT_INDEX | DBX_RESULT_INFO". The flags are:

  • DBX_RESULT_INDEX—Always returned. All results in the result array are indexed by a number, i.e., $result[0], $result[1], etc.

  • DBX_RESULT_INFO—Returns information about the columns returned, such as field name and field type.

  • DBX_RESULT_ASSOC—Sets the keys of the returned array to the column names.

The object returned by dbx_query contains the following properties:

  • handle—The same handle that is available from $dbconn->handle. Accessed as $result->handle.

  • cols—The number of columns in the result set. Accessed by $result->col.

  • rows—The number of rows in the result set. Accessed by $result->rows.

  • info—Returned 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.

  • data—Contains the actual data from result. Accessed by $result->data[$x]['field name'] where $x is the index of the particular row.


$result = dbx_query($dbconn, "select something from  some_table", DBX_RESULT_INFO);


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:

  • RESULT—The result of a previous dbx_query statement.

  • SORT FUNCTION—Your custom sort function.


function my_sort {
            //your custom sort definition
dbx_sort($result, "my_sort");
//$result is now sorted according to my_sort()


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:

  • ROW1—A result from a dbx_query function call.

  • ROW2—A result from a dbx_query function call.

  • COLUMN KEY—The name of the column on which the comparison should be made.

  • FLAGS—You 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_DESC—Compare in descending order.

  • DBX_CMP_NATIVE—(default) Compare the items "as is."

  • DBX_CMP_TEXT—Compare the items as strings.

  • DBX_CMP_NUMBER—Compare the items as numbers.


$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 3–1 shows dbx_urls.php in action.

Figure 3-1FIGURE 3–1 dbx_urls.php

Script 3–1 dbx_urls.php Script 3–8

  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,
  6.  </style>
  7.  </head>
  8.  <body>
  9.  <?
10.  /*****
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
19.  $server = "";
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',
35.      }elseif($action == "delete") {
36.         $url = urldecode($url);
37.          $sql = "delete from URLS where URL =
38.      }
39.      $result = @dbx_query($dbconn, $sql);
40.      if ( $result == 0 ) {
41.          echo "<P>ERROR ADDING URL: " .
42.      } else {
43.          print("<p>$action : $url
44.      }
45.  }
46.  /*** MAIN ***/
47.  $dbconn = dbx_connect($MODULE, $server, $database, $user, $password)
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
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
72.      <?
73.      for($i = 0; $i < sizeof($result->data); $i++) {
74.          ?>
75.          <tr><td><a
77.          <td width=1><a
78.          <?
79.      }
80.      ?></table><?
81.  }
82.  ?>
83.  </body>
84.  </html>

Script 3–1 dbx_urls.php Line-by-Line Explanation




Print out normal HTML to start the page.


The SQL statement required to create the table for this example.


The $MODULE definition for the type of database the script will access. Valid choices are defined in line 17.


Define the database server host name or IP.


Define the database user's username.


Define the database user's password.


Define the database name on the database server.


Define a function to query the database and return the URLs in the database.


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 function—for example, if the database is down. More information on handling these errors is available in Chapter 8.


If the $result == 0, then there was an error, because upon success, the dbx_query is supposed to return an object.


Print out the error if line 26 is true.


If there was no error, then return the result object.


End the function declaration.


Define a function to add or remove URLs from the database called url(). The function takes the following arguments:

$action—either "add" or "delete"

$dbconn—the connection link to the database

$url—the URL to be added or removed

$description—the description of the URL


If the $action argument is "add", then we are adding a URL.


Generate the SQL to add the URL.


If $action is not "add", then check to see if it is "delete".


Decode the encoded URL.


Generate the SQL to delete the URL.


End the if/else statement started on line 33.


Query the database with the generated SQL.


If the $result == 0, then there was an error, because upon success, the dbx_query is supposed to return an object.


Display an error to the user including the specific DBX error message.


If there wasn't an error querying the database, then display a success message to the user.


End the function.


Start the man program.


Generate the database connection string with the variables defined at the beginning of the script.


Print out the HTML for the page that displays the heading, as well as the form to add URLs.


If the "Add URL!" button has been pushed, then run the url() function.


If a "Delete" link has been clicked next to any of the URLs, then run the url() function.


Generate an SQL statement to retrieve the URLs.


Run the get_url() function using the SQL generated above to retrieve the URLs from the database.


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.


Display a message to the user that the database was empty.


If the database was not empty, then execute the rest of the script.


Create a table to display the URLs.


Start a for loop to loop through the data returned from the get_url() function.


Print out the URL to the table and include a hyperlink to the URL.


Print out the description of the URL to the table.


Print a delete link for the URL.


End the for loop.


End the if/else statement started on line 63.


Close out the HTML for the page.

  • + Share This
  • 🔖 Save To Your Account