We can create a table in a database using the CREATE TABLE query in MySQL. Let's create a simple table "Employees", consisting of five columns: "employeeID", "firstname", "lastname", "email" and "joining_date". The query will look something like this:
CREATE TABLE Employees(
employeeID INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
joining_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)
Let's break down the attributes:
This is how it will look in a PHP script:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "cwhDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// sql to create table
$sql = "CREATE TABLE Employees(
employeeID INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
joining_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)";
if ($conn->query($sql) === TRUE) {
echo "Table Employees created successfully";
} else {
echo "Error creating table: " . $conn->error;
}
$conn->close();
?>