
PHP MySQLi CREATE Table
In PHP, you can use MySQLi (MySQL Improved) to create a new table in a MySQL database using the mysqli_query()
function to execute SQL queries. Before creating a table, you need to establish a connection to the MySQL server using mysqli_connect()
. Here’s a step-by-step guide on how to create a new table in MySQL using MySQLi in PHP:
<?php
$servername = "localhost"; // Replace with your server name or IP address
$username = "your_username"; // Replace with your MySQL username
$password = "your_password"; // Replace with your MySQL password
$dbname = "your_database"; // Replace with your database name
// 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
$tableName = "your_new_table"; // Replace with the name you want for your 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 (mysqli_query($conn, $sql)) {
echo "Table created successfully.";
} else {
echo "Error creating table: " . mysqli_error($conn);
}
// Close the connection
mysqli_close($conn);
?>
In this example, we first create a connection to the MySQL server using mysqli_connect()
and then check if the connection is successful. Next, we define the name of the new table in the $tableName
variable.
The SQL query to create the new table is constructed in the $sql
variable. The CREATE TABLE
statement is used to create a new table in MySQL. In this example, we define a table with columns id
, firstname
, lastname
, email
, and reg_date
.
The id
column is defined as an auto-incremented primary key. The firstname
and lastname
columns are defined as VARCHAR with a maximum length of 30 characters and are marked as NOT NULL
, meaning they must have a value. The email
column is also a VARCHAR with a maximum length of 50 characters, and reg_date
is a TIMESTAMP column with a default value of the current timestamp.
We use the mysqli_query()
function to execute the SQL query. If the table creation is successful, it will print “Table created successfully.” Otherwise, it will display an error message.
Finally, we close the database connection using mysqli_close()
.
Remember to replace "your_username"
, "your_password"
, "your_database"
, and "your_new_table"
with your actual MySQL username, password, database name, and the desired name for the new table. Also, make sure that the MySQL user you are using has the necessary privileges to create a new table in the specified database.
Please exercise caution while running this script, as it has the potential to create a new table in your MySQL database. Always double-check your credentials and ensure that you are authorized to perform this operation.