63 lines
1.6 KiB
PHP
63 lines
1.6 KiB
PHP
<?php
|
||
// db/config.php
|
||
|
||
function db_connect() {
|
||
static $pdo;
|
||
if ($pdo) {
|
||
return $pdo;
|
||
}
|
||
|
||
// Database credentials - DO NOT MODIFY
|
||
$host = '127.0.0.1';
|
||
$dbname = 'app';
|
||
$user = 'app';
|
||
$pass = 'app';
|
||
$port = 3306;
|
||
$charset = 'utf8mb4';
|
||
|
||
$dsn = "mysql:host=$host;port=$port;dbname=$dbname;charset=$charset";
|
||
$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 ([31m[4mPDOException[0m $e) {
|
||
// In a real app, log this error and show a generic message
|
||
throw new [31m[4mPDOException[0m($e->getMessage(), (int)$e->getCode());
|
||
}
|
||
}
|
||
|
||
function run_migrations() {
|
||
$pdo = db_connect();
|
||
$migrationsDir = __DIR__ . '/migrations';
|
||
if (!is_dir($migrationsDir)) {
|
||
mkdir($migrationsDir, 0775, true);
|
||
}
|
||
|
||
$migrationFiles = glob($migrationsDir . '/*.sql');
|
||
sort($migrationFiles);
|
||
|
||
foreach ($migrationFiles as $file) {
|
||
try {
|
||
$sql = file_get_contents($file);
|
||
if (!empty(trim($sql))) {
|
||
$pdo->exec($sql);
|
||
}
|
||
} catch ([31m[4mPDOException[0m $e) {
|
||
// Log error, handle failure
|
||
error_log("Migration failed for file $file: " . $e->getMessage());
|
||
}
|
||
}
|
||
}
|
||
|
||
// Run migrations automatically on include
|
||
run_migrations();
|
||
|
||
// Helper function for easy access
|
||
function db() {
|
||
return db_connect();
|
||
} |