Database Migrations in PHP
Managing schema changes becomes chaotic without a versioning strategy. A migration system tracks every alteration to your database, enabling you to upgrade or downgrade environments reliably.
Creating a migrations table
Store applied migrations in a dedicated table. Each migration is a numbered PHP file that makes incremental changes.
CREATE TABLE schema_migrations (
id INT AUTO_INCREMENT PRIMARY KEY,
migration VARCHAR(255) NOT NULL,
applied_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
Writing a migration script
Each migration should contain an up() and down() function. The up() applies the change, the down() reverts it:
<?php
declare(strict_types=1);
function up(PDO $pdo): void {
$pdo->exec("ALTER TABLE users ADD COLUMN bio TEXT NULL");
}
function down(PDO $pdo): void {
$pdo->exec("ALTER TABLE users DROP COLUMN bio");
}
?>
Store this file as 20250101010101_add_bio_column.php. A simple runner can scan a migrations directory, execute new files and record them in schema_migrations.
Running migrations
When deploying, execute the runner. It will read all migration files, compare them against the table and run any pending ones in ascending order. This ensures all environments share the same schema history.