Dealing with databases

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://www.php.net/manual/en/ref.dba.php.

Application

This example creates a database and stores some informationin it.


<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>

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://www.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.

Join the PC World newsletter!

Error: Please check your email address.

Our Back to Business guide highlights the best products for you to boost your productivity at home, on the road, at the office, or in the classroom.

Keep up with the latest tech news, reviews and previews by subscribing to the Good Gear Guide newsletter.

Gavin Sherry

PC World
Show Comments

Essentials

Lexar® JumpDrive® S57 USB 3.0 flash drive

Learn more >

Microsoft L5V-00027 Sculpt Ergonomic Keyboard Desktop

Learn more >

Mobile

Lexar® JumpDrive® S45 USB 3.0 flash drive 

Learn more >

Exec

HD Pan/Tilt Wi-Fi Camera with Night Vision NC450

Learn more >

Lexar® JumpDrive® C20c USB Type-C flash drive 

Learn more >

Audio-Technica ATH-ANC70 Noise Cancelling Headphones

Learn more >

Lexar® Professional 1800x microSDHC™/microSDXC™ UHS-II cards 

Learn more >

Budget

Back To Business Guide

Click for more ›

Most Popular Reviews

Latest News Articles

Resources

PCW Evaluation Team

Michael Hargreaves

Windows 10 for Business / Dell XPS 13

I’d happily recommend this touchscreen laptop and Windows 10 as a great way to get serious work done at a desk or on the road.

Aysha Strobbe

Windows 10 / HP Spectre x360

Ultimately, I think the Windows 10 environment is excellent for me as it caters for so many different uses. The inclusion of the Xbox app is also great for when you need some downtime too!

Mark Escubio

Windows 10 / Lenovo Yoga 910

For me, the Xbox Play Anywhere is a great new feature as it allows you to play your current Xbox games with higher resolutions and better graphics without forking out extra cash for another copy. Although available titles are still scarce, but I’m sure it will grow in time.

Kathy Cassidy

STYLISTIC Q702

First impression on unpacking the Q702 test unit was the solid feel and clean, minimalist styling.

Anthony Grifoni

STYLISTIC Q572

For work use, Microsoft Word and Excel programs pre-installed on the device are adequate for preparing short documents.

Featured Content

Latest Jobs

Don’t have an account? Sign up here

Don't have an account? Sign up now

Forgot password?