Skip to content

Instantly share code, notes, and snippets.

@erikeldridge
Created April 21, 2010 06:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save erikeldridge/373491 to your computer and use it in GitHub Desktop.
Save erikeldridge/373491 to your computer and use it in GitHub Desktop.
a simple key/val store using php & sqlite
<?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