36525-vm/db/config.php
Flatlogic Bot 88faa8fb09 V1
2025-12-01 07:37:01 +00:00

45 lines
1.1 KiB
PHP

<?php
require_once __DIR__ . '/../lib.php';
load_env(__DIR__ . '/../.env');
function db(): ?PDO
{
static $pdo = null;
if ($pdo !== null) {
return $pdo;
}
$host = getenv('DB_HOST');
$port = getenv('DB_PORT');
$db = getenv('DB_DATABASE');
$user = getenv('DB_USERNAME');
$pass = getenv('DB_PASSWORD');
if (!$host || !$db || !$user) {
// You could log an error or throw an exception here
return null;
}
$dsn = "mysql:host={$host};port={$port};dbname={$db};charset=utf8mb4";
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
try {
$pdo = new PDO($dsn, $user, $pass, $options);
return $pdo;
} catch (PDOException $e) {
// In a real application, you'd log this error and show a generic error page.
// For development, it's okay to show the error.
// throw new PDOException($e->getMessage(), (int)$e->getCode());
error_log('DB Connection Error: ' . $e->getMessage());
return null;
}
}