DekGenius.com
Previous Section  < Day Day Up >  Next Section

13.10 SQLite

The SQLite embedded database engine comes bundled with PHP 5. An SQLite database is a single file. Inside that file are all the tables in a database. You don't need a separate database program running on your server to access an SQLite database—when your PHP program connects to the database, it opens the file, reads from it, and writes to it. For heavily trafficked sites, SQLite isn't as fast as a regular database program such as MySQL, but it is packed with features and is capable for small projects. Example 13-13 shows the answer to Exercise 7.1 using SQLite.

Example 13-13. Using the SQLite database
require 'DB.php';

$db = DB::connect('sqlite://:@localhost/restaurant.db');
if (DB::isError($db)) { die("Can't connect: " . $db->getMessage( )); }

$db->setErrorHandling(PEAR_ERROR_DIE);
$db->setFetchMode(DB_FETCHMODE_ASSOC);

$dishes = $db->getAll('SELECT dish_name,price FROM dishes ORDER BY price');

if (count($dishes) > 0) {
    print '<ul>';
    foreach ($dishes as $dish) {
        print "<li> $dish[dish_name] ($dish[price])</li>";
    }
    print '</ul>';
} else {
    print 'No dishes available.';
}

The only thing different about Example 13-13 and the answer (Section C.6.1) to Exercise 7.1 (Section 7.14) is the DSN supplied to DB::connect( ). The DSN for SQLite doesn't have a username or password, and instead of a database name, the last part of the DSN is the filename of the SQLite database file.

Chapter 4 of O'Reilly's Upgrading to PHP 5 discusses SQLite. You can also read about SQLite in the PHP Manual (http://www.php.net/sqlite).

    Previous Section  < Day Day Up >  Next Section