Dec 062013
 
Article PHP

The functionality offered by Berkeley DB has already been introduced in previous posts in this series, and sample use cases in Perl and Java have been presented. This post explains how to work with databases of this type in a PHP script.

Installing the Berkeley DB library for PHP

PHP distributions do not include a library for handling Berkely DB. This functionality is implemented as an extension that must be downloaded, compiled and enabled in the php configuration.

First, go to the Oracle Berkeley DB download page:

 http://www.oracle.com/technetwork/database/berkeleydb/downloads/index.html

From that page, download the file Berkeley DB 5.3.21.NC.tar.gz , without encryption (34M)

Uncompress the file downloaded, extract the contents and perform the installation with the commands:

Installing the db4 extension for PHP

In order to install the db4 extension, the PHP development package must be previously installed in the system.

On a Debian system, this is easily done with the “apt-get” command:

In the example above, we can see that apt-get install also the shtool command, and updates the version of other php packages installed. shtool is used internally by the installation scripts of many open source projects, as a replacement for older scripts such as mkdir.sh, install.sh, etc…

Next, the PHP db4.so extension is compiled:

 


Note: Depending on the versions of BDB and PHP installed on the system, the make command may fail with an error message:

This happens because in the last versions of PHP, ‘function_entry’ has been renamed to ‘zend_function_entry’.

This issue can be fixed by editing the file “db-5.3.21.NC/lang/php_db4/db4.cpp” and replacing, in line 149, the reference to  ‘function_entry’ by ‘zend_function_entry’. Next, issue again the commands “make” and “sudo make install”.


Then, install the extension:

Finally, edit the php configuration file (usually located at /etc/php5/cli/php.ini) to enable the extension just compiled, adding the line:

The methods implemented by this extension can be listed as follows:

Create/open a Berkeley DB file

We can open a database “test” in a file “/var/tmp/db4” with the command:

If the database did not exist previously, it is created.

Writing records

A record in the form of a pair (key, value) can be written to the database with the command:

Reading records

The record for a given key in the Berkeley database can be retrieved with the command:

Traverse the content of the database

To go through all the records in the database, a cursor is used as follows:

Related posts:

Index of posts related to PHP programming

 Posted by at 10:08 am

 Leave a Reply

(required)

(required)