35521-vm/db/migrate.php
2025-11-06 12:19:31 +00:00

37 lines
1.3 KiB
PHP

<?php
require_once 'config.php';
try {
// 1. Connect to MySQL server without specifying a database
$pdo_admin = new PDO('mysql:host='.DB_HOST.';charset=utf8mb4', DB_USER, DB_PASS, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
]);
echo "Connected to MySQL server successfully.\n";
// 2. Create the database if it doesn't exist
$pdo_admin->exec("CREATE DATABASE IF NOT EXISTS ".DB_NAME);
echo "Database '".DB_NAME."' created or already exists.\n";
// 3. Now, connect to the specific database using the existing helper
$pdo = db();
echo "Connected to database '".DB_NAME."' successfully.\n";
// 4. Run the table migration
$sql_file = __DIR__ . '/migrations/001_create_contacts_table.sql';
if (file_exists($sql_file)) {
$sql = file_get_contents($sql_file);
// PDO::exec can't handle multiple statements in one go, so we split them.
$statements = array_filter(array_map('trim', explode(';', $sql)));
foreach ($statements as $statement) {
if (!empty($statement)) {
$pdo->exec($statement);
}
}
echo "Migration from $sql_file applied successfully.\n";
} else {
echo "Migration file not found: $sql_file\n";
}
} catch (PDOException $e) {
die("Database operation failed: " . $e->getMessage());
}