Skip to content

Instantly share code, notes, and snippets.

@nfcg
Last active January 19, 2022 21:06
Show Gist options
  • Save nfcg/f2988cbb8355b504871c5f0e1612c464 to your computer and use it in GitHub Desktop.
Save nfcg/f2988cbb8355b504871c5f0e1612c464 to your computer and use it in GitHub Desktop.
<?php
function sqlite($method, $cmd)
{
global $database, $values;
try {
if (!file_exists($database)){throw new PDOException("database not found");}
$db = new PDO("sqlite:$database");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->exec("PRAGMA journal_mode = wal;");
switch ($method) {
case "query":
try {
$result = $db->query($cmd);
return $result->fetchALL(PDO::FETCH_ASSOC);
$db = null;
unset($db);
} catch (PDOException $e) {
echo "Connection Error -->> " .
$e->getMessage() .
"<BR />Error Code -->> " .
$e->getCode() .
"<BR />Error occur in File -->> " .
$e->getFile() .
"<BR />Error occur on Line no -->> " .
$e->getLine();
$db = null;
unset($db);
die();
}
break;
case "update":
try {
$update = $db->prepare($cmd);
$update->execute();
return $update->rowCount();
$db = null;
unset($db);
} catch (PDOException $e) {
echo "Connection Error -->> " .
$e->getMessage() .
"<BR />Error Code -->> " .
$e->getCode() .
"<BR />Error occur in File -->> " .
$e->getFile() .
"<BR />Error occur on Line no -->> " .
$e->getLine();
$db = null;
unset($db);
die();
}
break;
case "insert":
try {
$qry = $db->prepare($cmd);
$qry->execute($values);
return $db->lastInsertId();
$db = null;
unset($db);
} catch (PDOException $e) {
echo "Connection Error -->> " .
$e->getMessage() .
"<BR />Error Code -->> " .
$e->getCode() .
"<BR />Error occur in File -->> " .
$e->getFile() .
"<BR />Error occur on Line no -->> " .
$e->getLine();
$db = null;
unset($db);
die();
}
break;
default:
echo "Not Allowed";
exit();
}
} catch (PDOException $e) {
echo "Connection Error -->> " .
$e->getMessage() .
"<BR />Error Code -->> " .
$e->getCode() .
"<BR />Error occur in File -->> " .
$e->getFile() .
"<BR />Error occur on Line no -->> " .
$e->getLine();
$db = null;
unset($db);
die();
}
}
/*
$database = "./database.db";
$select = sqlite("query", "SELECT * from COMPANY;");
echo '<pre>';
print_r($select);
echo '</pre>';
$values = ["Nuno", 45, "None", 600.00];
$insert = sqlite("insert", "INSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY) VALUES (?,?,?,?,?);");
if ($insert == 0) {
echo "ERROR: " . $insert;
}
$update = sqlite("update", "UPDATE COMPANY set SALARY = 1200.00 where NAME = 'Nuno';");
if ($update == 0) {
echo "ERROR: " . $update;
}
$delete = sqlite("update", "DELETE from COMPANY where NAME = 'Nuno';");
if ($delete == 0) {
echo "ERROR: " . $delete;
}
*/
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment