What is the correct syntax for creating a table in MySQL using PHP?
When creating a table in MySQL using PHP, you need to establish a connection to the database, write the SQL query to create the table, and then execute the query using PHP functions. Make sure to handle any potential errors that may occur during the process.
<?php
// Establish a connection to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// SQL query to create a 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
)";
// Execute the query
if ($conn->query($sql) === TRUE) {
echo "Table created successfully";
} else {
echo "Error creating table: " . $conn->error;
}
// Close the connection
$conn->close();
?>
Keywords
Related Questions
- What are the potential drawbacks of using cookies to store form data in PHP applications?
- What are the advantages and disadvantages of using a heartbeat method instead of a cronjob for sending reminder emails in PHP?
- How can the issue of the FTP connection not being established be resolved in the PHP script?