What could be causing the error message "Table already exists" when creating a new table in PHP?

The error message "Table already exists" occurs when trying to create a table in a database that already exists with the same name. To solve this issue, you can check if the table exists before attempting to create it. If the table exists, you can either choose to drop it and recreate it or modify your code to handle the existing table.

<?php
// Connect to database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);

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

// Check if table exists
$tableName = "example_table";
$result = $conn->query("SHOW TABLES LIKE '$tableName'");
if($result->num_rows > 0) {
    // Table already exists, handle accordingly
    // For example, drop table and recreate it
    $conn->query("DROP TABLE $tableName");
}

// Create new table
$sql = "CREATE TABLE $tableName (
    id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    firstname VARCHAR(30) NOT NULL,
    lastname VARCHAR(30) NOT NULL,
    email VARCHAR(50),
    reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)";
if ($conn->query($sql) === TRUE) {
    echo "Table created successfully";
} else {
    echo "Error creating table: " . $conn->error;
}

$conn->close();
?>