Return to Snippet

Revision: 13175
at April 13, 2009 17:26 by Keef


Initial Code
/*
*	Description: Very simple and lightweight SQLite wrapper class, it also has some SQL injection protection.
*	License: Competely public domain with no warranty whatsoever.
*/

Class SQLiteDB {
	private $db;
	private $debug = true;
	var $argChar = '?';
	
	// For debugging purposes.
	var $statement;
	var $old_statements = array();
	
	function __construct($filename = null) {
		$this->open($filename);
	}
	
	function open($filename = null) {
		// If no file is specified create a temporary table in memory.
		if (empty($filename))
			$filename = ':memory:';
		
		if (!$this->db = sqlite_open($filename, 0666, $sqliteerror))
			die($sqliteerror);
	}
	
	function execute($statement, $arguments = null) {
		if (!empty($arguments)) {
			for ($i = 0; $i < count($arguments); $i++) {
				$arguments[$i] = "'". addslashes(htmlspecialchars($arguments[$i], ENT_QUOTES)). "'";
			}
			
			$statement = vsprintf(str_replace($this->argChar, '%s', $statement), $arguments);
		}
		
		// For debugging purposes.
		if ($debug) {
			$this->statement = $statement;
			$this->old_statements[] = $statement;
		}
		
		$rs = sqlite_query($this->db, $this->statement);
		
		return new ResultSet($rs);
	}
	
	function close() {
		sqlite_close($this->db);
	}
	
	function lastInsertRowId() {
		return sqlite_last_insert_rowid($db);
	}
}


Class ResultSet {
	private $rs;
	
	function __construct($rs) {
		$this->rs = $rs;
	}
	
	function isValidRow() {
		return sqlite_valid($this->rs);
	}
	
	function next() {
		return sqlite_next($this->rs);
	}
	
	function fieldCount() {
		$row = sqlite_current($this->rs);
		
		return (count($row) / 2);
	}
	
	function fieldName($fieldIndex) {
		return sqlite_field_name($this->rs, $fieldIndex);
	}
	
	function field($fieldIndex) {
		$row = sqlite_current($this->rs);
		
		return stripslashes(htmlspecialchars_decode($row[$fieldIndex]));
	}
}

Initial URL


Initial Description


Initial Title
SQLite lightweight wrapper

Initial Tags


Initial Language
PHP