42 lines
1.4 KiB
PHP
42 lines
1.4 KiB
PHP
<?php
|
|
// db/config.php
|
|
|
|
// --- Database Credentials ---
|
|
// --> IMPORTANT: Replace with your actual database credentials
|
|
define('DB_HOST', getenv('DB_HOST') ?: '127.0.0.1');
|
|
define('DB_PORT', getenv('DB_PORT') ?: 3306);
|
|
define('DB_NAME', getenv('DB_NAME') ?: 'localdb');
|
|
define('DB_USER', getenv('DB_USER') ?: 'user');
|
|
define('DB_PASS', getenv('DB_PASS') ?: 'password');
|
|
|
|
/**
|
|
* Establishes a PDO database connection.
|
|
*
|
|
* @return PDO|null A PDO connection object on success, or null on failure.
|
|
*/
|
|
function db_connect() {
|
|
static $pdo = null;
|
|
|
|
if ($pdo !== null) {
|
|
return $pdo;
|
|
}
|
|
|
|
$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);
|
|
return $pdo;
|
|
} catch (PDOException $e) {
|
|
// In a real application, you would log this error and show a generic message.
|
|
// For development, it's useful to see the error.
|
|
error_log('Database Connection Error: ' . $e->getMessage());
|
|
// Never show detailed errors in production
|
|
// die('Database connection failed. Please check configuration.');
|
|
return null;
|
|
}
|
|
} |