43 lines
1.3 KiB
PHP
43 lines
1.3 KiB
PHP
<?php
|
|
|
|
// Database configuration
|
|
define('DB_HOST', getenv('DB_HOST') ?: '127.0.0.1');
|
|
define('DB_PORT', getenv('DB_PORT') ?: '3306');
|
|
define('DB_NAME', getenv('DB_NAME') ?: 'main');
|
|
define('DB_USER', getenv('DB_USER') ?: 'admin');
|
|
define('DB_PASS', getenv('DB_PASS') ?: 'admin');
|
|
|
|
if (!function_exists('db')) {
|
|
/**
|
|
* Establishes a PDO database connection.
|
|
*
|
|
* @return PDO The PDO database connection object.
|
|
* @throws PDOException If the connection fails.
|
|
*/
|
|
function db(): PDO
|
|
{
|
|
static $pdo = null;
|
|
|
|
if ($pdo === null) {
|
|
$dsn = 'mysql:host=' . DB_HOST . ';port=' . DB_PORT . ';dbname=' . DB_NAME . ';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, DB_USER, DB_PASS, $options);
|
|
} catch (PDOException $e) {
|
|
// In a real app, you would 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());
|
|
}
|
|
}
|
|
|
|
return $pdo;
|
|
}
|
|
}
|
|
|
|
|