From 0fad0d3d32939084fae7ce3eb836d0ee5d45289b Mon Sep 17 00:00:00 2001 From: Josaphat Imani Date: Sat, 28 Sep 2024 09:55:24 +0200 Subject: [PATCH] Added code to raise exception on database errors --- lib/db.php | 25 ++++++++++++++++--------- 1 file changed, 16 insertions(+), 9 deletions(-) diff --git a/lib/db.php b/lib/db.php index 908aefb863..d5f7b8f09c 100644 --- a/lib/db.php +++ b/lib/db.php @@ -94,17 +94,23 @@ static public function execute($dbh, $sql, $args, $type = false, $all = false) { if (!$type) { $type = self::execute_type($sql); } - $sql = $dbh->prepare($sql); - if (!$sql || !$sql->execute($args)) { + try { + $sql = $dbh->prepare($sql); + if (!$sql || !$sql->execute($args)) { + return false; + } + if ($type == 'modify' || $type == 'insert') { + return $sql->rowCount(); + } + if ($all) { + return $sql->fetchAll(PDO::FETCH_ASSOC); + } + return $sql->fetch(PDO::FETCH_ASSOC); + } catch (PDOException $oops) { + Hm_Msgs::add('ERRDatabase error. Please try again.'); + Hm_Debug::add($oops->getMessage()); return false; } - if ($type == 'modify' || $type == 'insert') { - return $sql->rowCount(); - } - if ($all) { - return $sql->fetchAll(PDO::FETCH_ASSOC); - } - return $sql->fetch(PDO::FETCH_ASSOC); } /** @@ -139,6 +145,7 @@ static public function connect($site_config) { try { self::$dbh[$key] = new PDO($dsn, self::$config['db_user'], self::$config['db_pass']); self::$dbh[$key]->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); + self::$dbh[$key]->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); Hm_Debug::add(sprintf('Connecting to dsn: %s', $dsn)); return self::$dbh[$key]; } catch (Exception $oops) {