February 12, 2008

Simple Flat File Database

I had recently been refused access to a sql database for a project, this I started looking for other options. After a little searching I stumbled across txtSQL, which is a very powerful but easy to use flat file database.

To start off download the latest release (2.2 final at the time of writing this). Then read the read me in the doc folder it will walk you through setting up the include files you will need as well as the database folder, by default called data. One you have these placed correctly just like with mysql you will need to connect to the database.


include('includes/txtSQL.class.php');
$sql = new txtSQL('includes/data'); // Location of the database files
$sql->connect('root', ''); // This is the default name and password
$sql->selectdb('XXX'); // XXX is the database name


This will let you connect to the database you want to use, I do recommend changing the password from its default. However there is no database or tables right now so you should add these.


// txtSQL created a new database named testDatabase
$sql->createdb(array('db' => 'XXX')) or die('Error creating txtSQL DB, txtSQL said: '.$sql->get_last_error());

// Create Table in new database
$columns = array(
'id' => array('type' => 'int', 'auto_increment' => 1, 'permanent' => 1
'name' => array('type' => 'string', 'max' => 50),
'email' => array('type' => 'string', 'max' => 50) );

$sql->createtable(
'db' => 'testDb',
'table' => 'testTable',
'columns' => $columns);


Now you have tables set up, unlike sql databases, this is all commands with arrays, so it takes a little getting used to, but is not to horrible to learn. Finally, you just need to manipulate the data.


// Select
$where = 'somthing = '.$_POST['something'];
$results = $sql->execute('select', array('table' => 'XXX', 'where' => array('0' => $where), 'limit' => array(1)));

// Grab first result
$result = $results[0]; // Just want the first result

//or use them all
foreach($results as $result) // Grab each row from the result
{
//... Do something
}

// Insert
$insertvalues = array( 'name' => 'matt', 'date' => '9/8/06' );
$sql->execute('insert', array('table' => 'XXX', 'values' => $insertvalues));


The rest delete and update are also similar, and you can find example in the documentation included.
Although txtSQL is not a perfect replacement for a real sql database it does work rather well. However it is suggested that is only be used with smaller database needs, otherwise stick to a real real database management system. Still for what I needed it to do I am quite happy.

No comments: