handle DB errors

This commit is contained in:
Paul Spenke
2023-06-30 07:25:59 +08:00
parent 0fb1038202
commit fcde537871
+11 -9
View File
@@ -54,6 +54,7 @@ class DB
*/ */
public function all(string $table, $columns = '*') public function all(string $table, $columns = '*')
{ {
try {
if (is_array($columns)) { if (is_array($columns)) {
foreach ($columns as &$column) { foreach ($columns as &$column) {
$column = preg_replace('/[^a-zA-Z_]*/', '', $column); $column = preg_replace('/[^a-zA-Z_]*/', '', $column);
@@ -65,6 +66,13 @@ class DB
} }
$stmt->execute(); $stmt->execute();
return $stmt->fetchAll(); return $stmt->fetchAll();
} catch (\PDOException $e) {
$_SESSION["phpb_flash"] = [
'message-type' => 'error',
'message' => phpb_trans('website-manager.check-database')
];
return [];
}
} }
/** /**
@@ -109,18 +117,12 @@ class DB
} }
function tableExists($table) { function tableExists($table) {
// Try a select statement against the table
// Run it in try-catch in case PDO is in ERRMODE_EXCEPTION.
try { try {
$result = $this->pdo->query("SELECT 1 FROM {$table} LIMIT 1"); $this->pdo->query("SELECT 1 FROM {$table} LIMIT 1");
return TRUE;
} catch (Exception $e) { } catch (Exception $e) {
// We got an exception (table not found)
return FALSE; return FALSE;
} }
// Result is either boolean FALSE (no table found) or PDOStatement Object (table found)
return $result !== FALSE;
} }
/** /**
@@ -134,7 +136,7 @@ class DB
{ {
// check if table with the name $table exists. if not, execute $query.' // check if table with the name $table exists. if not, execute $query.'
try { try {
$result = $this->pdo->query("SELECT 1 FROM {$table} LIMIT 1"); $this->pdo->query("SELECT 1 FROM {$table} LIMIT 1");
return TRUE; return TRUE;
} catch (Exception $e) { } catch (Exception $e) {
$stmt = $this->pdo->prepare($sql); $stmt = $this->pdo->prepare($sql);