diff --git a/class_appdb.php b/class_appdb.php index 8057e4c..aff45ec 100644 --- a/class_appdb.php +++ b/class_appdb.php @@ -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; } }