How can PHP developers handle errors when attempting to create a database using CREATE DATABASE in their scripts?

When attempting to create a database using CREATE DATABASE in PHP scripts, developers can handle errors by using try-catch blocks to catch any exceptions that may occur during the database creation process. By wrapping the database creation code in a try block and catching any potential exceptions in a catch block, developers can gracefully handle errors and provide appropriate error messages to users.

try {
    $conn = new PDO("mysql:host=localhost", "username", "password");
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    $conn->exec("CREATE DATABASE dbname");
    
    echo "Database created successfully";
} catch (PDOException $e) {
    echo "Error creating database: " . $e->getMessage();
}