Team LiB
Previous Section Next Section

Writing Data

The data within a dba database file can be seen as an associative array that you may traverse entry by entry. So there is, unfortunately, no SQL access layer available; nevertheless, it is really easy to get data into the database.

The key function is dba_insert(), which inserts a new entry into the database file. You have to provide the key, the value, and the associated dba handle returned by dba_open(). Listing 26.3 inserts a few values into the database file.

Listing 26.3. Inserting Data into the dba File
<?php
  require_once "handler.inc.php";
  $dba = @dba_open("dba.db", "w", $dbahandler);
  if (!$dba) {
    echo "Failed opening database.";
  } else {
    if (dba_insert("John", "Coggeshall", $dba) &&
        dba_insert("Shelley", "Johnson", $dba) &&
        dba_insert("Damon", "Jordan", $dba)) {
      echo "Succeeded writing to database.";
      dba_close($dba);
    } else {
      echo "Failed writing to database.";
    }
  }
?>

Existing entries may be changed, as well. This is done by the function dba_replace(). This one is really effective: If the provided key does not exist, a new entry is generated; otherwise, an existing entry is replaced.

TIP

The conclusion is easy: Generally use dba_replace() instead of dba_insert(). Then you save the work of checking whether an entry exists. If are interested, the latter task can be done using dba_exists().


Listing 26.4 replaces one value (correcting a typo) and adds a new one.

Listing 26.4. Updating Data in the dba File
<?php
  require_once "handler.inc.php";
  $dba = @dba_open("dba.db", "w", $dbahandler);
  if (!$dba) {
    echo "Failed opening database.";
  } else {
    if (dba_replace("Shelley", "Johnston", $dba) &&
        dba_replace("Bill", "Gates", $dba)) {
      echo "Succeeded updating database.";
      dba_close($dba);
    } else {
      echo "Failed updating database.";
    }
  }
?>

Finally, dba_delete() removes entries by their name. In this case, the function returns whether this succeeded or not. In other words, if the entry does not exist, dba_delete() returns false. Listing 26.5 removes an unwanted entry in the list of people who worked on this book.

Listing 26.5. Deleting Data from the dba File
<?php
  require_once "handler.inc.php";
  $dba = @dba_open("dba.db", "w", $dbahandler);
  if (!$dba) {
    echo "Failed opening database.";
  } else {
    if (dba_delete("Bill", $dba)) {
      echo "Succeeded deleting from database.";
      dba_close($dba);
    } else {
      echo "Failed deleting from database.";
    }
  }
?>

    Team LiB
    Previous Section Next Section