How can one handle and analyze errors in table creation queries in PHP scripts?

When handling errors in table creation queries in PHP scripts, it is important to check for any errors returned by the database and handle them appropriately. One way to do this is by using the mysqli_error() function to retrieve the error message and display it to the user or log it for debugging purposes.

// Connect to the database
$mysqli = new mysqli("localhost", "username", "password", "database");

// Check for connection errors
if ($mysqli->connect_error) {
    die("Connection failed: " . $mysqli->connect_error);
}

// Create table query
$sql = "CREATE TABLE users (
    id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    firstname VARCHAR(30) NOT NULL,
    lastname VARCHAR(30) NOT NULL,
    email VARCHAR(50),
    reg_date TIMESTAMP
)";

// Execute the query and check for errors
if ($mysqli->query($sql) === TRUE) {
    echo "Table created successfully";
} else {
    echo "Error creating table: " . $mysqli->error;
}

// Close the connection
$mysqli->close();