Eliminate duplicate database instances. Clean up error responses.
This commit is contained in:
parent
7f68c60009
commit
b6b1dc8d8a
|
|
@ -13,37 +13,42 @@ class AppDB {
|
||||||
|
|
||||||
public static function getLastInsertId() {
|
public static function getLastInsertId() {
|
||||||
if ( is_null(self::$dbh) ) return 0;
|
if ( is_null(self::$dbh) ) return 0;
|
||||||
return self::$dbh->lastInsertId();
|
return intval(self::$dbh->lastInsertId());
|
||||||
}
|
}
|
||||||
|
|
||||||
public static function getSTH($query = "") {
|
public static function getSTH($query = "") {
|
||||||
if ( is_null(self::$dbh) ) self::getDBH();
|
|
||||||
if ( $query == "" ) return false;
|
if ( $query == "" ) return false;
|
||||||
|
if ( is_null(self::$dbh) ) self::getDBH();
|
||||||
return self::$dbh->prepare($query);
|
return self::$dbh->prepare($query);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static function getDBH() {
|
private static function getDBH() {
|
||||||
if ( !is_null(self::$dbh) ) return self::$dbh;
|
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 to connect to the database
|
||||||
try {
|
try {
|
||||||
if ( DBTYPE == "mysql" ) {
|
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" ) {
|
} else if ( DBTYPE == "sqlite" ) {
|
||||||
$dbh = new PDO("sqlite:" . SQLITEDB);
|
$dbh = new PDO("sqlite:" . SQLITEDB, null, null, $options);
|
||||||
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
|
|
||||||
$dbh->exec("PRAGMA foreign_keys = ON");
|
$dbh->exec("PRAGMA foreign_keys = ON");
|
||||||
} else {
|
} else {
|
||||||
throw new Exception("Bad database configuration in config file!");
|
throw new Exception("Bad database configuration in config file!");
|
||||||
exit();
|
|
||||||
}
|
}
|
||||||
} catch (PDOException | Exception $e) {
|
} catch (Exception $e) {
|
||||||
//header('Location: error_db.php?connection=');
|
error_log("DB connection failed: " . $e->getMessage());
|
||||||
echo "Couldn't connect to DB!";
|
http_response_code(500);
|
||||||
|
header("Content-Type: application/json");
|
||||||
|
echo json_encode(["error" => true, "message" => "Bad database configuration in config file!"]);
|
||||||
exit();
|
exit();
|
||||||
}
|
}
|
||||||
|
|
||||||
self::$dbh = $dbh;
|
self::$dbh = $dbh;
|
||||||
|
return $dbh;
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue
Block a user