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!

Error: Please check your email address.
Rocket to Success - Your 10 Tips for Smarter ERP System Selection
Keep up with the latest tech news, reviews and previews by subscribing to the Good Gear Guide newsletter.

Gavin Sherry

PC World
Show Comments

Cool Tech

Breitling Superocean Heritage Chronographe 44

Learn more >

SanDisk MicroSDXC™ for Nintendo® Switch™

Learn more >

Toys for Boys

Family Friendly

Panasonic 4K UHD Blu-Ray Player and Full HD Recorder with Netflix - UBT1GL-K

Learn more >

Stocking Stuffer

Razer DeathAdder Expert Ergonomic Gaming Mouse

Learn more >

Christmas Gift Guide

Click for more ›

Most Popular Reviews

Latest Articles

Resources

PCW Evaluation Team

Edwina Hargreaves

WD My Cloud Home

I would recommend this device for families and small businesses who want one safe place to store all their important digital content and a way to easily share it with friends, family, business partners, or customers.

Walid Mikhael

Brother QL-820NWB Professional Label Printer

It’s easy to set up, it’s compact and quiet when printing and to top if off, the print quality is excellent. This is hands down the best printer I’ve used for printing labels.

Ben Ramsden

Sharp PN-40TC1 Huddle Board

Brainstorming, innovation, problem solving, and negotiation have all become much more productive and valuable if people can easily collaborate in real time with minimal friction.

Sarah Ieroianni

Brother QL-820NWB Professional Label Printer

The print quality also does not disappoint, it’s clear, bold, doesn’t smudge and the text is perfectly sized.

Ratchada Dunn

Sharp PN-40TC1 Huddle Board

The Huddle Board’s built in program; Sharp Touch Viewing software allows us to easily manipulate and edit our documents (jpegs and PDFs) all at the same time on the dashboard.

George Khoury

Sharp PN-40TC1 Huddle Board

The biggest perks for me would be that it comes with easy to use and comprehensive programs that make the collaboration process a whole lot more intuitive and organic

Featured Content

Product Launch Showcase

Latest Jobs

Don’t have an account? Sign up here

Don't have an account? Sign up now

Forgot password?