setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // Create migrations table if it doesn't exist $pdo->exec("CREATE TABLE IF NOT EXISTS migrations ( id INT AUTO_INCREMENT PRIMARY KEY, migration_name VARCHAR(255) NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP )"); // Get all migration files $migrationFiles = glob(__DIR__ . '/migrations/*.sql'); // Get already run migrations $stmt = $pdo->query("SELECT migration_name FROM migrations"); $runMigrations = $stmt->fetchAll(PDO::FETCH_COLUMN); echo 'Database Migrations'; echo ''; echo ''; echo '
'; echo '

Database Migrations

'; $migrationsApplied = false; foreach ($migrationFiles as $file) { $migrationName = basename($file); if (!in_array($migrationName, $runMigrations)) { echo '
Applying migration: ' . htmlspecialchars($migrationName) . '...
'; $sql = file_get_contents($file); $statements = array_filter(array_map('trim', explode(';', $sql))); $fileHasError = false; foreach ($statements as $statement) { if (empty($statement)) continue; try { $pdo->exec($statement); } catch (PDOException $e) { // 1060 is the specific error code for "Duplicate column name" if (strpos($e->getMessage(), '1060') !== false) { // It's a duplicate column error, we can ignore it. echo '
Ignoring existing column in ' . htmlspecialchars($migrationName) . '.
'; } else { // It's another error, so we should stop. echo '
Error applying migration ' . htmlspecialchars($migrationName) . ': ' . htmlspecialchars($e->getMessage()) . '
'; $fileHasError = true; break; // break from statements loop } } } if (!$fileHasError) { // Record migration $stmt = $pdo->prepare("INSERT INTO migrations (migration_name) VALUES (?)"); $stmt->execute([$migrationName]); echo '
Successfully applied ' . htmlspecialchars($migrationName) . '
'; $migrationsApplied = true; } else { // Stop on error break; // break from files loop } } } if (!$migrationsApplied) { echo '
Database is already up to date.
'; } echo 'Back to Home'; echo '
'; } catch (PDOException $e) { http_response_code(500); die("Database connection failed: " . $e->getMessage()); }