exec(" CREATE TABLE IF NOT EXISTS schema_migrations ( version VARCHAR(255) NOT NULL PRIMARY KEY, applied_on TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); "); // 2. Get all migrations that have already been run $applied_migrations = $pdo->query("SELECT version FROM schema_migrations")->fetchAll(PDO::FETCH_COLUMN); } catch (PDOException $e) { die("A database error occurred during setup: " . $e->getMessage()); } // 3. Get all migration files on disk $migrationsDir = __DIR__ . '/migrations'; $all_files = glob($migrationsDir . '/*.sql'); sort($all_files); // 4. Determine and run new migrations foreach ($all_files as $file) { $filename = basename($file); if (!in_array($filename, $applied_migrations)) { echo "Applying migration: $filename\n"; try { $pdo->beginTransaction(); $sql = file_get_contents($file); $pdo->exec($sql); // Record the migration $stmt = $pdo->prepare("INSERT INTO schema_migrations (version) VALUES (?)"); $stmt->execute([$filename]); $pdo->commit(); echo " Success.\n"; } catch (PDOException $e) { if ($pdo->inTransaction()) { $pdo->rollBack(); } echo " Error applying migration $filename: " . $e->getMessage() . "\n"; // Stop on first error break; } } else { echo "Skipping already applied migration: $filename\n"; } } echo "Migrations completed.\n";