PHP provides several functions for DBA. The first function you must know is the dba_open() function. This will allow you to create a database, write to a database, read a database, or truncate a database.
int dba_open(string sPath, string sMode, string sHandler, [int nMod]);
The first parameter of the dba_open() function is the path to the database; the second parameter is the mode in which you wish to open the database. Possible values for this can be any of the following:
r – Open the database for reading.
w – Open the database for writing.
c – Create a new database.
n – Truncate a database.
The third parameter is the name of the handler for the type of database you would like to use. The third parameter can be any of the following values:
dbm – Berkley DB-style database (deprecated).
ndbm – A newer Berkley DB-style database. This is very limited and is also deprecated.
gdbm – The GNU database.
db3 – The DB3 database toolkit from Sleepycat Software. This will be the database type that you will use in your projects.
cdb – Qmail database. This format only supports reading operations.
The optional fourth parameter specifies the mode in which the database should open. This is not a commonly used parameter and you won’t be using it in your games.
The dba_open() function will return a handle for the database if it was successful; otherwise it returns 0 or false when it fails. This will allow you to verify that the database is open. If the open fails you can trap for it and either print a warning message or exit the application altogether. Take a look at the following code example to see how to use the dba_open() function.
<?php // Set the db parameters $dbPath = “myDatabase.db”; $dbType = “db3”; function CreateDatabase($thePath, $theType) { $db = dba_open($thePath, “c”, $theType); if(!$db) { printf(“Could not create the database”); return 0; } return $db; } function OpenDatabase($thePath, $theType) { $db = dba_open($thePath, “r”, $theType); if(!$db) { printf(“Could not open the database”); return 0; } return $db; } // Open the database, if it isn’t there, create it $db = OpenDatabase($dbPath, $dbType); if(!$db) { $db = CreateDatabase($dbPath, $dbType); if(!$db) { exit; } } // If you get here the database has opened successfully and you can do what you want with it. ?>