In MySQL, the CREATE TABLE statement is used to create a new table in the database. You define the table name, column names, data types, and constraints such as primary keys and auto-increment values. This is a foundational concept when working with MySQL through PHP.
// Basic MySQL CREATE TABLE syntax
CREATE TABLE table_name (
column1 datatype,
column2 datatype,
column3 datatype
);
This example creates a students table with an auto-increment primary key.
// Creating students table with primary key
CREATE TABLE students (
student_id INT AUTO_INCREMENT,
name VARCHAR(100),
age INT,
grade CHAR(1),
PRIMARY KEY (student_id)
);
After executing the query, MySQL creates the students table. Each new record automatically receives a unique student_id. The table is now ready for inserting and retrieving data through SQL or PHP scripts.
The following PHP code demonstrates how a PHP script sends a CREATE TABLE query to MySQL.
// PHP script to create a MySQL table
$conn = mysqli_connect("localhost","root","","school");
$sql = "CREATE TABLE students (
student_id INT AUTO_INCREMENT,
name VARCHAR(100),
age INT,
grade CHAR(1),
PRIMARY KEY (student_id)
)";
mysqli_query($conn, $sql);
AUTO_INCREMENT for unique identifiersemployees table with salary and hire datedepartment_id foreign keyDATE and FLOAT data types