Friday, October 14, 2011

PHP class for SQLite database (using PDO)

This class was created as a universal solution for small scripts that need to permanently store information in some kind of database. There are of course other ways like JSON/XML in files, or CDB, but using SQLite gives the flexibility of SQL without a need for any database server.

The following class uses PDO to interact with a database. It needs write permissions to a directory where the database file will be located. It turned out that the database becomes quite slow when tables grow to a half a million records so the class keeps the database in memory, flushing the data to a file when needed. It fits for a long lasting scripts because loading a large database to memory is not an easy task and script start may take some time.

This is a first version of the class and it needs some improvements, but it already helped me in a couple of tasks.

Here is a short usage snippet:
<?php

$db = new DB(
     DB_PATH.'db_name.sqlite', 
     'table_name', 
     array(
         'id' => 'INTEGER PRIMARY KEY AUTOINCREMENT', 
         'column1' => 'VARCHAR(1024) NOT NULL UNIQUE', 
         'column2' => 'VARCHAR(1024) NOT NULL'
     )
 );

?>