Eliminate duplicate database instances. Clean up error responses.

This commit is contained in:
Junior 2026-11-23 18:54:18 -05:00
parent 7f68c60009
commit b6b1dc8d8a

View File

@ -13,37 +13,42 @@ class AppDB {
public static function getLastInsertId() {
if ( is_null(self::$dbh) ) return 0;
return self::$dbh->lastInsertId();
return intval(self::$dbh->lastInsertId());
}
public static function getSTH($query = "") {
if ( is_null(self::$dbh) ) self::getDBH();
if ( $query == "" ) return false;
if ( is_null(self::$dbh) ) self::getDBH();
return self::$dbh->prepare($query);
}
private static function getDBH() {
if ( !is_null(self::$dbh) ) return self::$dbh;
$dbh = new PDO("mysql:host=" . DBHOST . ";dbname=" . DBNAME, DBUSER, DBPASS);
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_EMULATE_PREPARES => false,
];
// Try to connect to the database
try {
if ( DBTYPE == "mysql" ) {
$dbh = new PDO("mysql:host=" . DBHOST . ";dbname=" . DBNAME, DBUSER, DBPASS);
$dbh = new PDO("mysql:host=" . DBHOST . ";dbname=" . DBNAME . ";charset=utf8mb4",
DBUSER, DBPASS, $options);
} else if ( DBTYPE == "sqlite" ) {
$dbh = new PDO("sqlite:" . SQLITEDB);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbh = new PDO("sqlite:" . SQLITEDB, null, null, $options);
$dbh->exec("PRAGMA foreign_keys = ON");
} else {
throw new Exception("Bad database configuration in config file!");
exit();
}
} catch (PDOException | Exception $e) {
//header('Location: error_db.php?connection=');
echo "Couldn't connect to DB!";
} catch (Exception $e) {
error_log("DB connection failed: " . $e->getMessage());
http_response_code(500);
header("Content-Type: application/json");
echo json_encode(["error" => true, "message" => "Bad database configuration in config file!"]);
exit();
}
self::$dbh = $dbh;
return $dbh;
}
}