Looping through the Database

Now that you know how to create and open a non-relational database it would be handy to know how to loop through the data in the database to display it. To loop through a database record set you need to start at the very first key. PHP provides you with dba_firstkey() to get the first key of a specified database.

string dba_firstkey(int databaseHandle);

Once you retrieve the first key of the database you need to loop through each record until there are no more records. For this you will use a while loop because you won’t know the count of elements in the record set. To get the value, you use the dba_fetch() function.

string dba_fetch(string key, int databaseHandle);

The dba_fetch() function will return a string of false if it was unable to get the data. Once you have retrieved the data you will need to unserialize the data, just like you will have to serialize the data to put it into the database.

string unserialize(string someString);

After you have done this you can do what you want with the unserialized string. Then you need to retrieve the next key in order to move to the next record. Take a look at the fol-lowing example to see how it all works together:

<?php
$dbPath = “myDatabase.db”;
$dbType = “db3”;

$db = OpenDatabase($dbPath, $dbType);
if(!$db)
{
    $db = CreateDatabase($dbPath, $dbType);
    if(!$db)
    {
        exit;
    }
}

// Get the first record
$key = dba_firstkey($db);

// Loop through the whole database
while($key != false)
{
    $value = dba_fetch($key, $db);
    $entry = unserialize($value);
    // Do something with $entry
    $key = dba_nextkey($db);
}
dba_close($db);
?>

NOTE

Remember to always close the database you’re working with by using the dba_close() function.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset