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"?> <?xml version="1.0" encoding="UTF-8"?>
<project version="4"> <project version="4">
<component name="DataSourceManagerImpl" format="xml" multifile-model="true"> <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> <driver-ref>mysql.8</driver-ref>
<synchronize>true</synchronize> <synchronize>true</synchronize>
<jdbc-driver>com.mysql.cj.jdbc.Driver</jdbc-driver> <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> <working-dir>$ProjectFileDir$</working-dir>
</data-source> </data-source>
</component> </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_by_interpreter asDefaultInterpreter="true" interpreter_id="b74b3486-711a-42ad-bf18-c51cc1addaa5" timeout="30000" />
</phpcs_settings> </phpcs_settings>
</component> </component>
<component name="PhpProjectSharedConfiguration" php_language_level="7.0"> <component name="PhpProjectSharedConfiguration" php_language_level="8.2">
<option name="suggestChangeDefaultLanguageLevel" value="false" /> <option name="suggestChangeDefaultLanguageLevel" value="false" />
</component> </component>
<component name="PhpStan"> <component name="PhpStan">

View File

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

View File

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

View File

@ -4,6 +4,8 @@
// - setzt sinnvolle PHP-Error-Settings für die Entwicklung // - setzt sinnvolle PHP-Error-Settings für die Entwicklung
// - lädt die Rollen des eingeloggten Users bei jedem Request // - lädt die Rollen des eingeloggten Users bei jedem Request
require_once __DIR__ . '/db.php';
ini_set('display_errors', '1'); ini_set('display_errors', '1');
ini_set('display_startup_errors', '1'); ini_set('display_startup_errors', '1');
error_reporting(E_ALL); error_reporting(E_ALL);
@ -14,24 +16,22 @@ if (session_status() !== PHP_SESSION_ACTIVE) {
// Rollen bei jedem Request aus der DB aktualisieren // Rollen bei jedem Request aus der DB aktualisieren
if (!empty($_SESSION['user_id'])) { if (!empty($_SESSION['user_id'])) {
$__bsConn = new mysqli('localhost', 'FSST', 'L9wUNZZ9Qkbt', 'FSST', 3306); $__bsConn = db_connect();
if (!$__bsConn->connect_error) { $__bsStmt = $__bsConn->prepare(
$__bsStmt = $__bsConn->prepare( 'SELECT r.name FROM userRoles ur JOIN roles r ON r.roleID = ur.roleID WHERE ur.userID = ?'
'SELECT r.name FROM userRoles ur JOIN roles r ON r.roleID = ur.roleID WHERE ur.userID = ?' );
); if ($__bsStmt) {
if ($__bsStmt) { $__bsUid = (int)$_SESSION['user_id'];
$__bsUid = (int)$_SESSION['user_id']; $__bsStmt->bind_param('i', $__bsUid);
$__bsStmt->bind_param('i', $__bsUid); $__bsStmt->execute();
$__bsStmt->execute(); $__bsResult = $__bsStmt->get_result();
$__bsResult = $__bsStmt->get_result(); $_SESSION['user_roles'] = [];
$_SESSION['user_roles'] = []; while ($__bsRow = $__bsResult->fetch_assoc()) {
while ($__bsRow = $__bsResult->fetch_assoc()) { $_SESSION['user_roles'][] = $__bsRow['name'];
$_SESSION['user_roles'][] = $__bsRow['name'];
}
$__bsStmt->close();
} }
$__bsConn->close(); $__bsStmt->close();
} }
$__bsConn->close();
} else { } else {
$_SESSION['user_roles'] = []; $_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'; require_once __DIR__ . '/lib/bootstrap.php';
// 1) DB-Verbindung (einmal) // 1) DB-Verbindung (einmal)
$servername = "localhost"; $conn = db_connect();
$port = 3306;
$username = "FSST";
$password = "L9wUNZZ9Qkbt";
$db = "FSST";
$conn = mysqli_connect($servername, $username, $password, $db, $port);
if (!$conn)
{
http_response_code(500);
die("Datenbankfehler");
}
// 2) POST-Verarbeitung VOR jeglicher Ausgabe // 2) POST-Verarbeitung VOR jeglicher Ausgabe
$loginError = null; $loginError = null;

View File

@ -30,10 +30,7 @@ if (isset($_GET['categoryID']) && ctype_digit($_GET['categoryID'])) {
/* ======================= /* =======================
2) DB-Verbindung 2) DB-Verbindung
======================= */ ======================= */
$conn = new mysqli("localhost", "FSST", "L9wUNZZ9Qkbt", "FSST", 3306); $conn = db_connect();
if ($conn->connect_error) {
die("Datenbankfehler");
}
/* ======================= /* =======================
3) Kategorien laden 3) Kategorien laden
@ -89,10 +86,10 @@ $debugMode = isset($_GET['debug']) && $_GET['debug'] === '1';
$debugDetails = []; $debugDetails = [];
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['saveProduct'])) { if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['saveProduct'])) {
$model = trim($_POST['model']); $model = trim($_POST['model']);
$description = $_POST['description'] ?? null; $description = $_POST['description'] ?? null;
$categoryID = (int)$_POST['categoryID']; $categoryID = (int)$_POST['categoryID'];
$brandID = (int)($_POST['brandID'] ?? 0); $brandID = (int)($_POST['brandID'] ?? 0);
$imageUrl = trim((string)($_POST['imageUrl'] ?? '')); $imageUrl = trim((string)($_POST['imageUrl'] ?? ''));
$imageFile = (isset($_FILES['productImage']) && is_array($_FILES['productImage'])) ? $_FILES['productImage'] : null; $imageFile = (isset($_FILES['productImage']) && is_array($_FILES['productImage'])) ? $_FILES['productImage'] : null;
@ -130,8 +127,8 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['saveProduct'])) {
$saveError = 'Upload-Datei ungueltig.'; $saveError = 'Upload-Datei ungueltig.';
} else { } else {
$allowedMimeToExt = [ $allowedMimeToExt = [
'image/jpeg' => 'jpg', 'image/jpeg' => 'jpg',
'image/png' => 'png', 'image/png' => 'png',
]; ];
$mime = null; $mime = null;
@ -199,8 +196,8 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['saveProduct'])) {
$documentRoot = isset($_SERVER['DOCUMENT_ROOT']) ? (string)$_SERVER['DOCUMENT_ROOT'] : ''; $documentRoot = isset($_SERVER['DOCUMENT_ROOT']) ? (string)$_SERVER['DOCUMENT_ROOT'] : '';
$docRootTrim = rtrim($documentRoot, "\\/"); $docRootTrim = rtrim($documentRoot, "\\/");
$docTargetDir = ($docRootTrim !== '') $docTargetDir = ($docRootTrim !== '')
? $docRootTrim . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $relativeTargetDir) ? $docRootTrim . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $relativeTargetDir)
: ''; : '';
$targetDir = $dirTargetDir; $targetDir = $dirTargetDir;
if ($docTargetDir !== '' && !is_dir($dirTargetDir) && is_dir($docTargetDir)) { if ($docTargetDir !== '' && !is_dir($dirTargetDir) && is_dir($docTargetDir)) {
@ -268,7 +265,7 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['saveProduct'])) {
$valueString = null; $valueString = null;
$valueNumber = null; $valueNumber = null;
$valueBool = null; $valueBool = null;
if (is_numeric($value)) { if (is_numeric($value)) {
$valueNumber = $value; $valueNumber = $value;
@ -279,12 +276,12 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['saveProduct'])) {
} }
$stmtAttr->bind_param( $stmtAttr->bind_param(
"iisdi", "iisdi",
$productID, $productID,
$attributeID, $attributeID,
$valueString, $valueString,
$valueNumber, $valueNumber,
$valueBool $valueBool
); );
$stmtAttr->execute(); $stmtAttr->execute();
} }
@ -314,11 +311,12 @@ include 'header.php';
<form method="get" class="auth__form"> <form method="get" class="auth__form">
<div class="auth__select__wrap"> <div class="auth__select__wrap">
<label class="auth__select__label" for="categoryID">Kategorie</label> <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> <option value="">Kategorie wählen</option>
<?php foreach ($categories as $cat): ?> <?php foreach ($categories as $cat): ?>
<option value="<?= $cat['categoryID'] ?>" <option value="<?= $cat['categoryID'] ?>"
<?= $cat['categoryID'] === $categoryID ? 'selected' : '' ?>> <?= $cat['categoryID'] === $categoryID ? 'selected' : '' ?>>
<?= htmlspecialchars($cat['name']) ?> <?= htmlspecialchars($cat['name']) ?>
</option> </option>
<?php endforeach; ?> <?php endforeach; ?>
@ -381,9 +379,9 @@ include 'header.php';
</label> </label>
<input <input
type="<?= $attr['dataType'] === 'number' ? 'number' : 'text' ?>" type="<?= $attr['dataType'] === 'number' ? 'number' : 'text' ?>"
name="attributes[<?= $attr['attributeID'] ?>]" name="attributes[<?= $attr['attributeID'] ?>]"
class="auth__input" class="auth__input"
> >
<?php endforeach; ?> <?php endforeach; ?>

View File

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

View File

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

View File

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