Implement proper SQL error handling
And automatically create database if it does not exist.
This commit is contained in:
parent
1d95e1cc2d
commit
cb5afe3ac0
50
index.php
50
index.php
|
@ -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 />
|
||||
|
|
Loading…
Reference in New Issue