I’ve been working, gradually, on a project using an sqlite3 database (for its convenience) and found myself missing the clean elegance of wpdb… so I implemented it. It was actually really easy to do, and I figured I would throw it up here for anyone else wishing to use it. The functionality that I build this around is obtainable here: http://php-sqlite3.sourceforge.net/pmwiki/pmwiki.php (don’t freak… its in apt…)
With this I can focus on the sql, which is different enough, and not fumble over function names and such… $db = new sqlite_wpdb($dbfile, 3); var_dump($db->get_results(“SELECT * FROM `mytable` LIMIT 5”));
the code is below… and hopefully not too mangled…
< ?php
class sqlite_wpdb {
var $version = null;
var $db = null;
var $result = null;
var $error = null;
function sqwpdb($file, $version=3) {
return $this->__construct($file, $version);
}
function __construct($file, $version=3) {
$function = "sqlite{$version}_open";
if ( !function_exists($function) )
return false;
if ( !file_exists($file) )
return false;
if ( !$this->db = @$function($file) )
return false;
$this->version = $version;
$this->fquery = "sqlite{$this->version}_query";
$this->ferror = "sqlite{$this->version}_error";
$this->farray = "sqlite{$this->version}_fetch_array";
return $this;
}
function escape($string) {
return str_replace("'", "''", $string);
}
function query($query) {
if ( $this->result = call_user_func($this->fquery, $this->db, $query) )
return $this->result;
$this->error = call_user_func($this->ferror, $this->db);
return false;
}
function array_to_object($array) {
if ( ! is_array($array) )
return $array;
$object = new stdClass();
foreach ( $array as $idx => $val ) {
$object->$idx = $val;
}
return $object;
}
function get_results($query) {
if ( !$this->query($query) )
return false;
$rval = array();
while ( $row = $this->array_to_object(call_user_func($this->farray, $this->result)) ) {
$rval[] = $row;
}
return $rval;
}
function get_row($query) {
if ( ! $results = $this->get_results($query) )
return false;
return array_shift($results);
}
function get_var($query) {
return $this->get_val($query);
}
function get_val($query) {
if ( !$row = $this->get_row($query) )
return false;
$row = get_object_vars($row);
if ( !count($row) )
return false;
return array_shift($row);
}
function get_col($query) {
if ( !$results = $this->get_results($query) )
return false;
$column = array();
foreach ( $results as $row ) {
$row = get_object_vars($row);
if ( !count($row) )
continue;
$column[] = array_shift($row);
}
return $column;
}
}
?>
