refactor: centralize database connection logic and improve error handling

This commit is contained in:
Fabian Schieder 2026-03-18 15:33:28 +01:00
parent c13a3f62b3
commit 6aa7c4a764
13 changed files with 107 additions and 133 deletions

4
.idea/dataSources.xml generated
View File

@ -1,11 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="DataSourceManagerImpl" format="xml" multifile-model="true">
<data-source source="LOCAL" name="FSST" uuid="f9586db9-d1df-45a2-a60a-9a8716a08fec">
<data-source source="LOCAL" name="VPS" uuid="f9586db9-d1df-45a2-a60a-9a8716a08fec">
<driver-ref>mysql.8</driver-ref>
<synchronize>true</synchronize>
<jdbc-driver>com.mysql.cj.jdbc.Driver</jdbc-driver>
<jdbc-url>jdbc:mysql://localhost:3306/FSST</jdbc-url>
<jdbc-url>jdbc:mysql://localhost:3306/</jdbc-url>
<working-dir>$ProjectFileDir$</working-dir>
</data-source>
</component>

2
.idea/php.xml generated
View File

@ -15,7 +15,7 @@
<phpcs_by_interpreter asDefaultInterpreter="true" interpreter_id="b74b3486-711a-42ad-bf18-c51cc1addaa5" timeout="30000" />
</phpcs_settings>
</component>
<component name="PhpProjectSharedConfiguration" php_language_level="7.0">
<component name="PhpProjectSharedConfiguration" php_language_level="8.2">
<option name="suggestChangeDefaultLanguageLevel" value="false" />
</component>
<component name="PhpStan">

View File

@ -10,30 +10,18 @@ if (empty($_SESSION['user_id']))
$userId = (int)$_SESSION['user_id'];
$servername = "localhost";
$port = 3306;
$username = "FSST";
$password = "L9wUNZZ9Qkbt";
$db = "FSST";
$conn = db_connect();
$conn = mysqli_connect($servername, $username, $password, $db, $port);
if (!$conn)
{
$stmt = $conn->prepare('SELECT userID, displayName, email, profilePicture FROM users WHERE userID = ? LIMIT 1');
if (!$stmt) {
http_response_code(500);
die("Datenbankfehler");
die('Datenbankfehler');
}
$stmt = mysqli_prepare($conn, "SELECT userID, displayName, email, profilePicture FROM users WHERE userID = ? LIMIT 1");
if (!$stmt)
{
http_response_code(500);
die("Datenbankfehler");
}
$stmt->bind_param('i', $userId);
$stmt->execute();
mysqli_stmt_bind_param($stmt, "i", $userId);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$result = $stmt->get_result();
if ($result)
{
@ -44,8 +32,8 @@ else
$user = null;
}
mysqli_stmt_close($stmt);
mysqli_close($conn);
$stmt->close();
$conn->close();
if (!$user)
{

View File

@ -1,23 +1,14 @@
<?php
// login.php
require_once __DIR__ . '/lib/bootstrap.php';
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
// 1) DB-Verbindung (einmal)
$servername = "localhost";
$port = 3306;
$username = "FSST";
$password = "L9wUNZZ9Qkbt";
$db = "FSST";
$conn = mysqli_connect($servername, $username, $password, $db, $port);
if (!$conn)
{
http_response_code(500);
die("Datenbankfehler");
}
$conn = db_connect();
?>
<?php

View File

@ -4,6 +4,8 @@
// - setzt sinnvolle PHP-Error-Settings für die Entwicklung
// - lädt die Rollen des eingeloggten Users bei jedem Request
require_once __DIR__ . '/db.php';
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);
@ -14,8 +16,7 @@ if (session_status() !== PHP_SESSION_ACTIVE) {
// Rollen bei jedem Request aus der DB aktualisieren
if (!empty($_SESSION['user_id'])) {
$__bsConn = new mysqli('localhost', 'FSST', 'L9wUNZZ9Qkbt', 'FSST', 3306);
if (!$__bsConn->connect_error) {
$__bsConn = db_connect();
$__bsStmt = $__bsConn->prepare(
'SELECT r.name FROM userRoles ur JOIN roles r ON r.roleID = ur.roleID WHERE ur.userID = ?'
);
@ -31,7 +32,6 @@ if (!empty($_SESSION['user_id'])) {
$__bsStmt->close();
}
$__bsConn->close();
}
} else {
$_SESSION['user_roles'] = [];
}

17
lib/config.php Normal file
View File

@ -0,0 +1,17 @@
<?php
// Zentrale Konfiguration
// Hinweis: In Produktion idealerweise per Environment-Variablen setzen.
declare(strict_types=1);
return [
'db' => [
'host' => getenv('GEIZKRAGEN_DB_HOST') ?: 'localhost',
'port' => (int)(getenv('GEIZKRAGEN_DB_PORT') ?: 3306),
'user' => getenv('GEIZKRAGEN_DB_USER') ?: 'FSST',
'pass' => getenv('GEIZKRAGEN_DB_PASS') ?: 'L9wUNZZ9Qkbt',
'name' => getenv('GEIZKRAGEN_DB_NAME') ?: 'FSST',
'charset' => getenv('GEIZKRAGEN_DB_CHARSET') ?: 'utf8mb4',
],
];

32
lib/db.php Normal file
View File

@ -0,0 +1,32 @@
<?php
declare(strict_types=1);
/**
* Liefert eine MySQLi-Verbindung anhand der zentralen Konfiguration.
*
* Nutzung:
* $conn = db_connect();
*/
function db_connect(): mysqli
{
static $cfg;
if ($cfg === null) {
/** @var array{db: array{host:string,port:int,user:string,pass:string,name:string,charset:string}} $cfg */
$cfg = require __DIR__ . '/config.php';
}
$db = $cfg['db'];
$conn = new mysqli($db['host'], $db['user'], $db['pass'], $db['name'], $db['port']);
if ($conn->connect_error) {
http_response_code(500);
die('Datenbankfehler');
}
// Einheitliches Charset (wichtig für Umlaute/Emojis & Sicherheit)
$conn->set_charset($db['charset']);
return $conn;
}

View File

@ -4,18 +4,7 @@
require_once __DIR__ . '/lib/bootstrap.php';
// 1) DB-Verbindung (einmal)
$servername = "localhost";
$port = 3306;
$username = "FSST";
$password = "L9wUNZZ9Qkbt";
$db = "FSST";
$conn = mysqli_connect($servername, $username, $password, $db, $port);
if (!$conn)
{
http_response_code(500);
die("Datenbankfehler");
}
$conn = db_connect();
// 2) POST-Verarbeitung VOR jeglicher Ausgabe
$loginError = null;

View File

@ -30,10 +30,7 @@ if (isset($_GET['categoryID']) && ctype_digit($_GET['categoryID'])) {
/* =======================
2) DB-Verbindung
======================= */
$conn = new mysqli("localhost", "FSST", "L9wUNZZ9Qkbt", "FSST", 3306);
if ($conn->connect_error) {
die("Datenbankfehler");
}
$conn = db_connect();
/* =======================
3) Kategorien laden
@ -314,7 +311,8 @@ include 'header.php';
<form method="get" class="auth__form">
<div class="auth__select__wrap">
<label class="auth__select__label" for="categoryID">Kategorie</label>
<select id="categoryID" name="categoryID" class="auth__select" onchange="this.form.submit()" required>
<select id="categoryID" name="categoryID" class="auth__select" onchange="this.form.submit()"
required>
<option value="">Kategorie wählen</option>
<?php foreach ($categories as $cat): ?>
<option value="<?= $cat['categoryID'] ?>"

View File

@ -4,18 +4,7 @@
require_once __DIR__ . '/lib/bootstrap.php';
// 1) DB-Verbindung (einmal)
$servername = "localhost";
$port = 3306;
$username = "FSST";
$password = "L9wUNZZ9Qkbt";
$db = "FSST";
$conn = mysqli_connect($servername, $username, $password, $db, $port);
if (!$conn)
{
http_response_code(500);
die("Datenbankfehler");
}
$conn = db_connect();
$productId = isset($_GET['id']) ? (int)$_GET['id'] : 0;
?>

View File

@ -6,18 +6,7 @@ require_once __DIR__ . '/lib/bootstrap.php';
require_once __DIR__ . '/lib/strings.php';
// 1) DB-Verbindung (einmal)
$servername = "localhost";
$port = 3306;
$username = "FSST";
$password = "L9wUNZZ9Qkbt";
$db = "FSST";
$conn = mysqli_connect($servername, $username, $password, $db, $port);
if (!$conn)
{
http_response_code(500);
die("Datenbankfehler");
}
$conn = db_connect();
$errors = [];
$values = [

View File

@ -121,16 +121,8 @@ $publicPath = 'assets/images/profilePictures/' . $filename;
$servername = "localhost";
$port = 3306;
$username = "FSST";
$password = "L9wUNZZ9Qkbt";
$db = "FSST";
$conn = mysqli_connect($servername, $username, $password, $db, $port);
if (!$conn)
{
header('Location: account.php?upload=err');
exit();
}
$conn = db_connect();
$stmt = mysqli_prepare($conn, "UPDATE users SET profilePicture = ? WHERE userID = ?");
if (!$stmt)
@ -143,7 +135,7 @@ if (!$stmt)
mysqli_stmt_bind_param($stmt, 'si', $publicPath, $userId);
$ok = mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
mysqli_close($conn);
$conn->close();
if (!$ok)
{

View File

@ -4,18 +4,7 @@
require_once __DIR__ . '/lib/bootstrap.php';
// 1) DB-Verbindung (einmal)
$servername = "localhost";
$port = 3306;
$username = "FSST";
$password = "L9wUNZZ9Qkbt";
$db = "FSST";
$conn = mysqli_connect($servername, $username, $password, $db, $port);
if (!$conn)
{
http_response_code(500);
die("Datenbankfehler");
}
$conn = db_connect();
// Login-Check + Redirect MUSS vor jeglicher HTML-Ausgabe passieren
if (!isset($_SESSION['user_id'])) {