How can the SHOW CREATE TABLE command in PHP be utilized to retrieve table structures for dynamic table creation?

When dynamically creating tables in PHP, you may need to retrieve the structure of an existing table to use as a template. The SHOW CREATE TABLE command in PHP can be utilized to retrieve the table structure in the form of a CREATE TABLE statement, which can then be executed to create a new table with the same structure.

<?php
// Connect to the 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);
}

// Get table structure using SHOW CREATE TABLE command
$tableName = "existing_table";
$result = $conn->query("SHOW CREATE TABLE $tableName");
$row = $result->fetch_assoc();
$createTableStatement = $row['Create Table'];

// Create new table using the retrieved structure
$newTableName = "new_table";
$conn->query($createTableStatement);

echo "Table $newTableName created successfully with the same structure as $tableName.";

// Close connection
$conn->close();
?>