← Back to Chapters

MySQL CREATE TABLE

? MySQL CREATE TABLE

? Quick Overview

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.

? Key Concepts

  • Tables store structured data in rows and columns
  • Each column must have a defined data type
  • Constraints enforce data integrity
  • Primary keys uniquely identify records

⚙️ Syntax / Theory

? View Code Example
// Basic MySQL CREATE TABLE syntax
CREATE TABLE table_name (
column1 datatype,
column2 datatype,
column3 datatype
);

? Example: Create a Students Table

This example creates a students table with an auto-increment primary key.

? View Code Example
// 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)
);

? Live Output / Explanation

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.

? PHP + MySQL Interactive Example

The following PHP code demonstrates how a PHP script sends a CREATE TABLE query to MySQL.

? View Code Example
// 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);

? Use Cases

  • Creating user tables for login systems
  • Designing databases for student or employee records
  • Structuring e-commerce product catalogs
  • Defining tables for CMS and admin panels

✅ Tips & Best Practices

  • Always define a primary key for each table
  • Choose appropriate data types to save storage
  • Use AUTO_INCREMENT for unique identifiers
  • Plan table structure before writing PHP code

? Try It Yourself

  • Create an employees table with salary and hire date
  • Add a department_id foreign key
  • Experiment with DATE and FLOAT data types
  • Run the query using PHP and MySQLi