Implement proper SQL error handling

And automatically create database if it does not exist.
This commit is contained in:
Florine W. Dekker 2021-03-22 21:03:56 +01:00
parent 1d95e1cc2d
commit cb5afe3ac0
Signed by: FWDekker
GPG Key ID: B1B567AF58D6EE0F
2 changed files with 50 additions and 12 deletions

View File

@ -7,20 +7,40 @@ if ($path == "/admin") {
}
$db = new SQLite3(".links.db", SQLITE3_OPEN_READWRITE);
$stmt = $db->prepare("SELECT * FROM links WHERE path = :path;");
$stmt->bindValue(":path", $path);
$result = $stmt->execute()->fetchArray(SQLITE3_ASSOC);
$error = false;
$target = null;
try {
// Connect
if (!file_exists(".links.db")) {
$db = new SQLite3(".links.db");
$db->query(file_get_contents("links.sql"));
} else {
$db = new SQLite3(".links.db", SQLITE3_OPEN_READWRITE);
}
$db->enableExceptions(true);
if ($result) {
$stmt = $db->prepare("UPDATE links SET visits = visits + 1, last_visit = CURRENT_TIMESTAMP WHERE path = :path;");
// Get path
$stmt = $db->prepare("SELECT * FROM links WHERE path = :path;");
$stmt->bindValue(":path", $path);
$stmt->execute();
}
$db->close();
if ($result = $stmt->execute()->fetchArray(SQLITE3_ASSOC))
$target = $result["target"];
if ($result) {
$target = $result["target"];
// Update count
if ($target != null) {
$stmt = $db->prepare("UPDATE links SET visits = visits + 1, last_visit = CURRENT_TIMESTAMP
WHERE path = :path;");
$stmt->bindValue(":path", $path);
$stmt->execute();
}
// Close
$db->close();
} catch (Exception $exception) {
$error = true;
}
if ($target != null) {
header("Location: {$target}");
exit();
}
@ -58,7 +78,13 @@ if ($result) {
<div id="wrapper">
<h1><a href="https://fwdekker.com/">FWDekker</a></h1>
<?php
if ($path != "/") {
if ($error) {
?>
<b>Internal server error</b><br /><br />
Something went wrong internally, and you could not be redirected. Please try again later.<br /><br />
<br /><br />
<?php
} else if ($path != "/") {
?>
<b>Link not found</b><br /><br />
The short URL https://fwdkr.co<?= $path ?> could not be found.<br /><br />

12
links.sql Normal file
View File

@ -0,0 +1,12 @@
create table links
(
path text not null
constraint links_pk
primary key,
target text not null,
visits int default 0 not null,
last_visit text
);
create unique index links_path_uindex
on links (path);