Created
April 21, 2010 06:18
-
-
Save erikeldridge/373491 to your computer and use it in GitHub Desktop.
a simple key/val store using php & sqlite
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// a simple key/val store using php & sqlite | |
// license: http://gist.github.com/375593 | |
class SqliteStore { | |
function __construct($tableName, $filePath = 'db.sqlite') { | |
$this->tableName = sqlite_escape_string($tableName); | |
if (is_numeric($tableName[0])) { | |
$details = sprintf( | |
"sqlite will choke on table names that start w/ a number. yours starts w/ '%s'", | |
$tableName[0] | |
); | |
throw new Exception($details); | |
} | |
$this->db = new SQLiteDatabase($filePath, 0777, $errorMessage); | |
//wrap in try/catch & ignore warnings as workaround to lack of 'if not exists' in sqlite version | |
try { | |
$sql = "create table $tableName ( key text primary key, value text )"; | |
@$this->db->query( $sql ); | |
} catch ( Exception $e ) { | |
// var_dump($e); | |
} | |
} | |
function get($key) { | |
$sql = sprintf( | |
"SELECT value FROM %s WHERE key = '%s';", | |
$this->tableName, $key | |
); | |
$result = $this->db->query($sql)->fetch(SQLITE_ASSOC); | |
if ($result) { | |
$result = $result['value']; | |
} | |
return $result; | |
} | |
function set($key, $value){ | |
$time = time(); | |
$sql = sprintf( | |
"REPLACE INTO %s (key, value) VALUES ('%s', '%s');", | |
$this->tableName, sqlite_escape_string($key), sqlite_escape_string($value) | |
); | |
//allow exceptions to bubble up | |
$this->db->queryExec($sql); | |
} | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment