Team LiB
Previous Section Next Section

Sample Application

To conclude this chapter, we present a simple demo script that tries to open the big picture to larger applications using PHP'S dba functions. We create a simple, yet effective, news board. The administrator enters new postings into an HTML form; these postings are then written into a dba file. On another page, all news are read from the dba file, sorted, and then sent to the Web browser.

First is the form to write data into the database. It is a rather simple one, providing only two text input fields:

<form method="post">
News title: <input type="text" name="title"><br>
News text: <textarea rows="5" cols="70" name="text"></textarea><br>
<input type="submit" value="Enter news">
</form>

In the head of this document, this data is taken and then entered into the database, as we have done previously. However, you may remember that there is only one value per key. In this case, we use a little trick. First, we need a key that's unique. Since PHP 5, date() supports the parameter "c" to return an ISO8601 date ("2004-12-24T12:34:56+00:00"). This is a good unique key. (At least for sites that have not too many hits. To make quite sure that this is unique, we add a random number at the end.)

$timestamp = date("c") . mt_rand();

Now $timestamp serves as the key, but what about the value? This is easy, as well: The data from the HTML form is saved in an array. This is serialized using serialize()and voila, we have a string value that can be saved into the dba file.

$values = array("title" => $_POST["title"],
                "text" => $_POST["text"]);
$values = serialize($values);

Listing 26.7 implements all this; Figure 26.3 shows how this looks in the Web browser.

Listing 26.7. Entering Data into the News Database
<html>
<head>
<title>dba</title>
</head>
<body>
<?php
  if (isset($_POST["title"]) && isset($_POST["text"])) {
    $timestamp = date("c") . mt_rand();
    $values = array("title" => $_POST["title"],
                    "text" => $_POST["text"]);
    $values = serialize($values);
    require_once "handler.inc.php";
    if (!file_exists("news.db")) {
      @dba_open("news.db", "n", $dbahandler);
    }
    $dba = @dba_open("news.db", "w", $dbahandler);
    if (!$dba) {
      echo "Failed opening database.";
    } else {
      if (dba_insert($timestamp, $values, $dba)) {
        echo "Succeeded writing to database.";
        dba_close($dba);
      } else {
        echo "Failed writing to database.";
      }
    }
  }
?>
<form method="post">
News title: <input type="text" name="title"><br>
News text: <textarea rows="5" cols="70" name="text"></textarea><br>
<input type="submit" value="Enter news">
</form>
</body>
</html>

Figure 26.3. The mask to enter data into the news database.


The nextand laststep is to read this information from the database. This, however, proves to be a bit trickier than the things we've done before. The reason is that we would like to read out the information from the database in reverse order, the newest entry first. Usually, the last entry modified (not entered!) is the last entry in the database. So reading out all entries and then reversing the order does not always work out as planned. Therefore, we have to implement the following strategy:

1.
All information in the dba file has to be read in and saved locally in an array.

2.
This array has to be sorted by the keys. Because they are ISO8601 dates, they are perfectly sortable.

Let's start with retrieving the information from the database. This is done as before, using dba_firstkey(), dba_nextkey(), and dba_fetch(). Because the data we get is strings, but we want the arrays, we use unserialize().

<?php
  require_once "handler.inc.php";
  $dba = @dba_open("news.db", "r", $dbahandler);
  if (!$dba) {
    echo "Failed opening news database.";
  } else {
    echo "<ul>";
    if ($key = dba_firstkey($dba)) {
      do {
        $info[$key] = unserialize(dba_fetch($key, $dba));
      } while ($key = dba_nextkey($dba));
      dba_close($dba);
    } else {
      echo "Error reading from news database (or no entries available).";
    }
  }
?>

Now the keys in this array are sorted, largest entry first.

krsort($info);
reset($info);

Finally, all information is sent to the browser:

while (list($key, $value) = each($info)) {
  printf("<p><b>%s</b></p><p>%s</p><br>",
         htmlspecialchars($value["title"]),
         htmlspecialchars($value["text"]));
}

Listing 26.8 contains the complete code for this Web page; the result can be seen in Figure 26.4.

Listing 26.8. All Entries from the News Database
<?php
  require_once "handler.inc.php";
  $dba = @dba_open("news.db", "r", $dbahandler);
  if (!$dba) {
    echo "Failed opening news database.";
  } else {
    echo "<ul>";
    if ($key = dba_firstkey($dba)) {
      do {
        $info[$key] = unserialize(dba_fetch($key, $dba));
      } while ($key = dba_nextkey($dba));
      dba_close($dba);
      krsort($info);
      reset($info);
      while (list($key, $value) = each($info)) {
        printf("<p><b>%s</b></p><p>%s</p><br>",
               htmlspecialchars($value["title"]),
               htmlspecialchars($value["text"]));
      }
    } else {
      echo "Error reading from news database (or no entries available).";
    }
  }
?>

Figure 26.4. All data from the news database.


    Team LiB
    Previous Section Next Section