36947-vm/db/config.php
Flatlogic Bot 4be8924eba Educ8
2025-12-14 21:05:45 +00:00

26 lines
867 B
PHP

<?php
function db() {
static $p;
if ($p) return $p;
// Read credentials from environment variables
$dbName = getenv('DB_NAME') ?: 'my_database';
$dbHost = getenv('DB_HOST') ?: '127.0.0.1';
$dbPort = getenv('DB_PORT') ?: '3306';
$dbUser = getenv('DB_USER') ?: 'user';
$dbPass = getenv('DB_PASS') ?: 'password';
$dsn = "mysql:host={$dbHost};port={$dbPort};dbname={$dbName};charset=utf8mb4";
try {
$p = new PDO($dsn, $dbUser, $dbPass, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
]);
return $p;
} catch (PDOException $e) {
// In a real app, you'd log this error and show a generic message
throw new PDOException($e->getMessage(), (int)$e->getCode());
}
}