SQLite Data Access Class
Ever noticed how there aren’t any simple SQLITE data access classes on the web?
I looked everywhere for one, and couldn’t find one that was simple ans sensible. So I decided to write one.
Here it is:
<?php
//so basically the same as last time, only encapsolated in a class, and without test functions that are unused.
class litedb
{
//do the dimming!
public $db;
public $result;
public $i;
public $token;
public $tRecords;
public $runQuery;
public $sqliteerror;
//open the database connection.
function open()
{
//change if database changes.
$db = sqlite_open(‘../dataStore.sdb’, 0666, $sqliteerror);
return $db;
}
//open and query.
function q($token)
{
$db = $this->open();
$result = sqlite_query($db, $token);
$runQuery = array();
$i = 0;
//loop into an array.
while (sqlite_has_more($result))
{
$runQuery[$i] = sqlite_fetch_array($result, SQLITE_ASSOC);
$i++;
}
$tRecords = count($runQuery);
sqlite_close($db);
if ($tRecords > 0)
{
//if we have something return it
return $runQuery;
}
else
{
//if we don’t call it nothing.
return ‘nothing’;
}
}
}
?>
Still with me? Good. Now, if you know your loops, you’ll also know that there are any number of ways to actually get to your dataset. My preferred method is the simple for loop. Also bear in mind that I like to do multi dimensional datasets because it enables me to do more with the data, without having to requery or commit temp data to the database. So, in terms of usage, here’s how I would access it. You, of course may want to do it differently.
//run your query
<?php
//call the class
$db = new litedb;
$data = $db->q(’select id from directory_employees order by id desc’);//count your records
$counter = count($data);
//if your ds is not empty run this:
if ($data != ‘nothing’)
{
for ($i = 0; $i < $counter; $i++)
{
echo($data[$i][‘id’]);
}
}
else
{
//otherwise, if it is empty run this
echo(‘no records’);
}
?>
Or if your prefer a foreach style loop:
<?php
if ($data != ‘nothing’)
{
foreach ($data as $dataRow)
{
echo($dataRow[‘id’]);
}
}
else
{
//otherwise, if it is empty run this
echo(‘no records’);
}
?>
You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed.

