Dealing with databases in PHP

Previously we have looked at building a basic address book database system. Address Book 1 stored its data in a flat file format - that is, plain text. The problem with storing data like this is that it is inefficient to search the entire address book line by line to locate a particular entry. Moreover, to search multiple fields of an entry - such as last name and suburb - required additional code.

Python vs. PHP: Choosing your next project's language

Database systems attempt to address this problem by storing data in mathematical patterns to speed retrieval. They also offer simple interfaces to these (quite complex) underlying algorithms so that the programmer does not need to worry about the best way to store and retrieve data for an application. As such, the programmer can work on developing the application without worrying too much about the data itself.

PHP includes interfaces for at least 20 different databases, including embedded databases such as dbm and Berkeley DB; popular commercial SQL databases including Oracle, IBM DB2, MS SQL and Sybase; as well as several sophisticated open source SQL databases including PostgreSQL and MySQL.

Embedded databases are a good place to begin when learning how to build database-backed applications. They are 'embedded' because they are accessed from within the application, unlike many SQL databases, which require network connections.

PHP provides a Database Abstraction (DBA) layer for several database systems, including dbm, ndbm, gdbm, Berkeley DB2 and DB3 (www.sleepycat.com) and cdb. This interface allows PHP developers to build basic data stores for their PHP applications with little fuss.

UNIX-style operating systems usually ship with at least one of the supported databases. PHP is not built to support embedded databases by default. Information on how to do this can be found at http://download.php.net/manual/en/ref.dba.php.

Application


This example (see code at end) creates a database and stores some information in it.

When accessed from a PHP-enabled Web server, this script creates a Berkeley DB3 database with the function dba_open(). This function accepts three arguments. The first is the full path to and filename of the database; in the example, this is set to /tmp/hereshow.db. The second argument is the mode in which to open the database; we have used the mode "n". This means that the database will be created if it does not exist or deleted and recreated if it does exist. It is then opened with read and write access. The third argument is the database driver to use - in this case, db3 means Berkeley DB3 (this script will work with all of the supported databases).

A full list of database modes and drivers can be found at http://downloads.php.net/manual/en/ref.dba.php.

The dba_open() function returns a database handler $id which is used in conjunction with the other dba functions. In the example script, if $id is set to false, dba_open() could not open the database and the script fails.

If $id is valid, the script attempts to insert some data into the databases with the function dba_insert(). This function takes three arguments: the first is the 'key', the next is the value of the key and the third is the database handler.

A database key is an identifier that can be used by the application to locate stored information. In the current example, the script is inserting only trivial data for the key. The power of key-based searching reveals itself when you consider the embedded database as a solution to a problem with Address Book 1. When used to search the data file, the script tested every line to see if it held a last name - more than 90 per cent of the time, it didn't.

Replaced with an embedded database system, the last name could be made the key to the database while the rest of the data could be inserted as the value (the second argument to dba_insert()) related to that key. Better still, by default the DBA layer creates B-Tree structured databases - the performance of which greatly outstrips that of linear searching.

The third argument to dba_insert() is the database identifier.

Finally, the last block of code in the example retrieves the data written to the database with the key $key. If the key is found (which it always should be in this example) then the data is returned to the user; otherwise, an error is raised. Test this by altering the value of $key after the data is inserted in the database. The script will return an error.

After this, the database handler is closed. As with fopen(), this is necessary in order to save data written to the database.

Next month, we will look at redesigning Address Book 1 to use the DBA layer.example:

<HTML>
<BODY>
<?
$id = dba_open("/tmp/hereshow.db","n","db3");
if(!$id) {
  exit("Could not open database /tmp/hereshow.db");
}
$key = time();
if(!dba_insert($key,"Time in seconds",$id)) {
  dba_close($id);
  exit("Could not update database /tmp/hereshow.db");
} else {
  echo "Successfully updated database with key = $key<br/>";
}
if(($value = dba_fetch($key,$id))) {
  echo "Found key $key with value $value<br/>";
} else {
  echo "Could not find key $key<br/>";
}dba_close($id);
?>
</BODY>
</HTML>

Join the newsletter!

Or

Sign up to gain exclusive access to email subscriptions, event invitations, competitions, giveaways, and much more.

Membership is free, and your security and privacy remain protected. View our privacy policy before signing up.

Error: Please check your email address.

More about etworkHewlett-Packard AustraliaHPIBM AustraliaIBM AustraliaMySQLOracleSybase Australia

Show Comments
[]