What is the best practice for creating tables in MySQL using PHP?
When creating tables in MySQL using PHP, it is best practice to use the mysqli extension for improved security and performance. This involves establishing a connection to the MySQL database, executing a CREATE TABLE query, and handling any errors that may occur during the process.
<?php
// Establish connection to MySQL database
$connection = mysqli_connect("localhost", "username", "password", "database");
// Check connection
if (mysqli_connect_errno()) {
die("Connection failed: " . mysqli_connect_error());
}
// Create table query
$query = "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
)";
// Execute query and check for errors
if (mysqli_query($connection, $query)) {
echo "Table created successfully";
} else {
echo "Error creating table: " . mysqli_error($connection);
}
// Close connection
mysqli_close($connection);
?>