PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, ]; try { // Try connecting to the database directly $pdo = new PDO($dsn . ';dbname=' . DB_NAME, DB_USER, DB_PASS, $options); } catch (PDOException $e) { // If the database doesn't exist, create it if (strpos($e->getMessage(), 'Unknown database') !== false) { try { $tempPdo = new PDO($dsn, DB_USER, DB_PASS, $options); $tempPdo->exec('CREATE DATABASE IF NOT EXISTS `' . DB_NAME . '`'); // Now, connect to the newly created database $pdo = new PDO($dsn . ';dbname=' . DB_NAME, DB_USER, DB_PASS, $options); } catch (PDOException $ce) { throw new PDOException("Failed to create database and connect: " . $ce->getMessage()); } } else { throw new PDOException("Database connection failed: " . $e->getMessage()); } } return $pdo; }