36525-vm/db/config.php
Flatlogic Bot 232ed5c114 V3
2025-12-01 09:10:54 +00:00

44 lines
1.1 KiB
PHP

<?php
require_once __DIR__ . '/../lib.php';
$_ENV = array_merge($_ENV, load_env(__DIR__ . '/../.env'));
function db(): ?PDO
{
static $pdo = null;
if ($pdo !== null) {
return $pdo;
}
$host = $_ENV['DB_HOST'] ?? null;
$port = $_ENV['DB_PORT'] ?? null;
$db = $_ENV['DB_DATABASE'] ?? null;
$user = $_ENV['DB_USERNAME'] ?? null;
$pass = $_ENV['DB_PASSWORD'] ?? null;
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.
error_log('DB Connection Error: ' . $e->getMessage());
return null;
}
}