35109-vm/db/config.php
2025-10-22 13:28:04 +00:00

63 lines
1.6 KiB
PHP
Raw Permalink Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?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 (PDOException $e) {
// In a real app, log this error and show a generic message
throw new PDOException($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 (PDOException $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();
}