PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, PDO::ATTR_EMULATE_PREPARES => false, ]); $pdo_init->exec('CREATE DATABASE IF NOT EXISTS `' . DB_NAME . '`'); // Now connect to the specific database $dsn = 'mysql:host=' . DB_HOST . ';port=' . DB_PORT . ';dbname=' . DB_NAME . ';charset=utf8mb4'; $pdo = new PDO($dsn, DB_USER, DB_PASS, [ PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, PDO::ATTR_EMULATE_PREPARES => false, ]); run_migrations($pdo); return $pdo; } catch (PDOException $e) { // In a real app, you'd log this error and show a generic message throw new PDOException($e->getMessage(), (int)$e->getCode()); } } function run_migrations($pdo) { $pdo->exec('CREATE TABLE IF NOT EXISTS `migrations` (`migration` VARCHAR(255) NOT NULL, PRIMARY KEY (`migration`))'); $applied_migrations = $pdo->query('SELECT `migration` FROM `migrations`')->fetchAll(PDO::FETCH_COLUMN); $migration_files = glob(__DIR__ . '/migrations/*.sql'); sort($migration_files); foreach ($migration_files as $file) { $migration_name = basename($file); if (!in_array($migration_name, $applied_migrations)) { $sql = file_get_contents($file); $pdo->exec($sql); $stmt = $pdo->prepare('INSERT INTO `migrations` (`migration`) VALUES (?)'); $stmt->execute([$migration_name]); } } }