48 lines
1.2 KiB
PHP
48 lines
1.2 KiB
PHP
<?php
|
|
// db/config.php
|
|
|
|
function db_connect() {
|
|
static $pdo;
|
|
|
|
if ($pdo) {
|
|
return $pdo;
|
|
}
|
|
|
|
$host = '127.0.0.1';
|
|
$db = 'app';
|
|
$user = 'root';
|
|
$pass = '';
|
|
$charset = 'utf8mb4';
|
|
|
|
$dsn = "mysql:host=$host;dbname=$db;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();
|
|
$migration_dir = __DIR__ . '/migrations';
|
|
$files = glob($migration_dir . '/*.sql');
|
|
sort($files);
|
|
|
|
foreach ($files as $file) {
|
|
try {
|
|
$sql = file_get_contents($file);
|
|
$pdo->exec($sql);
|
|
} catch (\PDOException $e) {
|
|
// Log error if needed, but continue
|
|
// This might happen if the table already exists, which is fine for idempotent scripts
|
|
}
|
|
}
|
|
} |