PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, ]); // Create the database if it doesn't exist $pdo->exec('CREATE DATABASE IF NOT EXISTS `'.DB_NAME.'`'); // Re-connect to the specific database $pdo = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME.';charset=utf8mb4', DB_USER, DB_PASS, [ PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, ]); } catch (PDOException $e) { // If database creation fails, it's a critical error. error_log('Database connection or creation failed: ' . $e->getMessage()); // Exit or handle the error gracefully. For a web request, you might show a generic error page. http_response_code(500); echo "Database connection failed. Please check the server logs."; exit; } } return $pdo; } function run_migrations() { $pdo = db(); $migrations_dir = __DIR__ . '/migrations'; if (!is_dir($migrations_dir)) { return; } $files = glob($migrations_dir . '/*.sql'); foreach ($files as $file) { $sql = file_get_contents($file); try { $pdo->exec($sql); } catch (PDOException $e) { // Log error or handle it as needed error_log("Migration failed for file: " . basename($file) . " with error: " . $e->getMessage()); } } } run_migrations();