Opening a Database
You can open a DBM-like database with the function dba_open(). This function requires three arguments: The path to the database file, a string containing the flags with which you want to open the database, and a string representing the database manager you want to work with (the 'type' column in Table 11.1). dba_open() returns a DBA resource that you can then pass to other DBA functions to access or manipulate your database. Because dba_open() involves reading from and writing to files, PHP must have permission to write to the directory that will contain your database.
The flags that you pass to dba_open() determine the way in which you can work with your database. They are listed in Table 11.2
Table 11.2 Flags for Use with dba_open()
Flag |
Description |
r |
Opens database reading only |
w |
Opens database for writing and reading |
c |
Creates database (or open for read/write access if it exists) |
n |
Creates new database (truncate old version if it exists) |
The following code fragment opens a database, creating a new one if it does not already exist:
$dbh = dba_open( "./data/products", "c", "gdbm" ) or die( "Couldn't open Database" );
Notice that we use a die() statement to end script execution if our attempt to open the database fails.
When you finish working with a database, close it using the function dba_close(). This is because PHP locks a database that you are working with so that other processes cannot attempt to modify the data you are reading or writing. If you don't close the database, then other processes are going to have to wait longer before getting their bite of the cherry. dba_close() requires a valid DBA resource:
dba_close( $dbh );