Skip to content

Instantly share code, notes, and snippets.

@bohwaz
Last active November 22, 2021 14:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bohwaz/f1dc723dd6fd1ade4260356f10ecbe61 to your computer and use it in GitHub Desktop.
Save bohwaz/f1dc723dd6fd1ade4260356f10ecbe61 to your computer and use it in GitHub Desktop.
Simple PHP wrapper around SQLite3
<?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