Simple PHP wrapper around SQLite3
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 | |
/* | |
* $db = new DB('file.sqlite'); | |
* var_dump($db->simple('SELECT * FROM table WHERE name = ?;', 'My Name')); | |
* var_dump($db->simpleSingle('SELECT * FROM table WHERE date > ? LIMIT 1;', '2020-01-01')); | |
* var_dump($db->simpleColumn('SELECT birthdate FROM table WHERE name = ?;', 'David Lynch')); | |
*/ | |
class DB extends \SQLite3 | |
{ | |
public function quote(string $str): string | |
{ | |
return '\'' . $this->escapeString($str) . '\''; | |
} | |
public function simpleStatement(string $sql, ... $params): ?\SQLite3Stmt | |
{ | |
$st = $this->prepare($sql); | |
foreach ($params as $key => $value) { | |
if (is_string($key)) { | |
$key = ':' . $key; | |
} | |
else { | |
$key++; | |
} | |
$st->bindValue($key, (string) $value); | |
} | |
return $st; | |
} | |
public function simple(string $sql, ... $params): ?array | |
{ | |
$res = $this->simpleStatement($sql, ... $params); | |
$res = $res->execute(); | |
$out = []; | |
while ($row = $res->fetchArray(\SQLITE3_ASSOC)) { | |
$out[] = (object) $row; | |
} | |
return $out; | |
} | |
public function simpleColumn(string $sql, ... $params) | |
{ | |
$res = $this->simpleStatement($sql, ... $params); | |
$res = $res->execute(); | |
$res = $res ? $res->fetchArray(\SQLITE3_NUM) : null; | |
return $res[0] ?? null; | |
} | |
public function simpleSingle(string $sql, ... $params): ?\stdClass | |
{ | |
$res = $this->simpleStatement($sql, ... $params); | |
$res = $res->execute(); | |
if ($res) { | |
$res = (object) $res->fetchArray(\SQLITE3_ASSOC); | |
} | |
return $res; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment