<?php
class database {
	//query types supported, see the `query` method for descriptions
	const query_standard     = 0;
	const query_array        = 1;
	const query_single       = 2;
	const query_single_array = 3;
	const query_prepare      = 4;
	
	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 (automatically creates the file on disk if it doesn’t exist)
		$this->handle = new PDO ('sqlite:'.$this->filepath);
		
		//if the database is new, build the tables from the sql originally passed to the class
		if (!$populate) $this->exec ($this->sql);
	}
	
	//execute sql statement(s) without returning a recordset. instead returns true/false for success
	public function exec ($sql) {
		//no connection is made to the database until a query is made
		if (!isset ($this->handle)) $this->connect ();
		return $this->handle->exec ($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 ();
		
		return 	//return the entire results as an array
			$mode == self::query_array  ? $this->handle->query ($sql)->fetchAll (PDO::FETCH_NUM) : (
			//return just the value of the very first column of the first row
			$mode == self::query_single ? $this->handle->query ($sql)->fetchColumn () : (
			//return a flat array of the first value of each row
			$mode == self::query_single_array
			? $this->handle->query ($sql)->fetchAll (PDO::FETCH_COLUMN) : (
			//compile an sql query for repeat execution
			$mode == self::query_prepare ? $this->handle->prepare ($sql)
			//else: return a standard result set
			: $this->handle->query ($sql, PDO::FETCH_NUM)
		)));
	}
	
	function __destruct () {
		$this->handle = null;
	}
}
?>