How can I create a random table with random name in PHP and MySql

 

In this article , we are going to demonstrates the how to create a random table with a random name using PHP and Mysql.

How can I create a random table with random name with PHP and SQL



<!DOCTYPE html>
<html>
<head>
	<title>Create Random Table</title>
</head>
<body>

<?php

// Establish a connection to the MySQL server
$host = "localhost"; 
$username = "root"; 
$password = "password"; 
$database = "mydatabase"; 
$conn = mysqli_connect($host, $username, $password, $database);

// Generate a random table name
$table_name = "table_" . rand(1000, 9999);

// Create the random table
$sql = "CREATE TABLE $table_name (
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 (mysqli_query($conn, $sql)) {
    echo "Table $table_name created successfully";
} else {
    echo "Error creating table: " . mysqli_error($conn);
}

// Close the database connection
mysqli_close($conn);

?>

</body>
</html>



This code first establishes a connection to the MySQL server using the "mysqli_connect()" function. It then generates a random table name using the "rand()" function and concatenates it with the string "table_". The code then creates a SQL query to create a table with the randomly generated name, and executes it using the "mysqli_query()" function. Finally, the code closes the database connection using the "mysqli_close()" function.


Previous Post Next Post