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 12.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 you pass to dba_open() determine the way in which you can work with your database. They are listed in Table 12.2.
Table 12.2. Flags for Use with dba_open()
Open a database for reading only
Open a database for writing and reading
Create a database (or open for read/write access if it exists)
Create a new database (truncate the 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, you should close it using the function dba_close(). This is because PHP locks a database 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, other processes have to wait longer before using the database. dba_close() requires a valid DBA resource:
dba_close( $dbh );
As of PHP 4.3, you can extend the flag you pass to dba_open() to allow for fine-grained control of database locking. Because basic locking is implemented by default, these details are beyond the scope of this book. You can, however, find more information at http://www.php.net/manual/en/function.dba.open.php.