Home > Articles > Programming > PHP

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:

--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:

  • 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.

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:

  • 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.

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:

  • RESULT—The result of a previous dbx_query statement.

  • SORT FUNCTION—Your 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:

  • 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.

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 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,
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>&nbsp;</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 3–1 dbx_urls.php Line-by-Line Explanation

LINE

DESCRIPTION

1–8

Print out normal HTML to start the page.

10–16

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 function—for 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.

28–30

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:

$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

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.

42–44

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.

49–53

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

55–57

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

58–60

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.

70–71

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.

83–84

Close out the HTML for the page.


InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020