PHP MySQL Create Table

Creating a MySQL table using PHP involves executing a SQL query that creates a new table within a database. Here’s an example of how to create a new MySQL table using PHP:

<?php
// MySQL server configuration
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mydatabase";
// Create a connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check the connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}
// Create a new table
$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 DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)";
if (mysqli_query($conn, $sql)) {
    echo "Table users created successfully";
} else {
    echo "Error creating table: " . mysqli_error($conn);
}
// Close the connection
mysqli_close($conn);
?>

In this example, we first define the configuration for the MySQL server by specifying the server name, username, and password. We also specify the name of the database we want to work with in the $dbname variable. We then create a connection to the server and select the appropriate database using the mysqli_connect() function.

Next, we define the structure of the new table we want to create in the $sql variable using SQL syntax. In this example, we create a table called “users” with columns for id, firstname, lastname, email, and reg_date. We also specify that the id column is the primary key and is auto-incremented, and that the reg_date column has a default value of the current timestamp.

We then execute the SQL query using the mysqli_query() function and check if it was successful. If it was successful, we print a message indicating that the table was created successfully. Otherwise, we print an error message with the details of the error using the mysqli_error() function.

Finally, we close the connection using the mysqli_close() function.