<?php //sqlite2 database class / written by kroc camen of camen design

class database {
	const query_standard     = 0;
	const query_unbuffered   = 1;
	const query_exec         = 2;
	const query_array        = 3;
	const query_single       = 4;
	const query_single_array = 5;
	
	private $filepath;
	private $handle;
	private $sql;
	
	function __construct ($filepath, $sql = '') {
		$this->filepath = $filepath;
		$this->sql      = $sql;
	}
	
	private function connect () {
		//does the database file exist on disk?
		$populate = file_exists ($this->filepath);
		//connect to the database ()
		$this->handle = sqlite_open  ($this->filepath);
		//if the database is new, build the tables from the sql originally passed to the class
		if (!$populate) $this->exec ($this->sql);
	}
	
	public function exec ($sql) {
		//no connection is made to the database until a query is made
		if (!isset ($this->handle)) $this->connect ();
		//do not return any rowset (for `INSERT` &c. queries), just true/false
		return sqlite_exec ($this->handle, $sql);
	}
	
	public function query ($sql, $mode = self::query_standard) {
		//no connection is made to the database until a query is made
		if (!isset ($this->handle)) $this->connect ();
		
		//this block is going to mash your head in >:]
		return	//return a fast, forward-only set (can’t use `rowCount` on this)
			$mode == self::query_unbuffered
			? sqlite_unbuffered_query ($this->handle, $sql) : (
			//return just the value of the very first column of the first row
			$mode == self::query_single
			? sqlite_fetch_single (sqlite_unbuffered_query ($this->handle, $sql)) : (
			//return the entire results as an array (best for <45 results)
			$mode == self::query_array
			? sqlite_array_query ($this->handle, $sql, SQLITE_NUM) : (
			//return a flat array of the first value of each row
			$mode == self::query_single_array
			? array_map (
				create_function ('$a', 'return $a[0];'),
				sqlite_array_query ($this->handle, $sql, SQLITE_NUM)
			)
			//return a standard result set
			: sqlite_query ($this->handle, $sql)
		)));
	}
	
	//use these with the object returned from a standard_query
	public function rowCount ($result) {
		return sqlite_num_rows ($result);
	}
	
	public function fetchRow ($result) {
		return sqlite_fetch_array ($result, SQLITE_NUM);
	}
	
	public function fetchArray ($result) {
		return sqlite_fetch_array ($result, SQLITE_ASSOC);
	}
	
	function __destruct () {
		if (isset ($this->handle)) sqlite_close ($this->handle);
	}
}
?>