PHP MySQL Create Table
In this page:
CREATE TABLE table_name (
id INT AUTO_INCREMENT PRIMARY KEY,
column1 VARCHAR(100) NOT NULL,
column2 VARCHAR(100) UNIQUE,
column3 INT DEFAULT 0
);
Defining a Basic Table Structure
A CREATE TABLE statement lists each column's name and data type -- id INT, name VARCHAR(100), email VARCHAR(100) -- describing exactly what shape of data the table will hold, before any rows are ever inserted.
- Choose column types that match the data as precisely as reasonable:
- INT for whole numbers
- VARCHAR(n) for short text with a sensible length limit
- TEXT for longer free-form content.
Example: Defining a Basic Table Structure
<?php
// Create a new `SQLite3` instance with ':memory:', stored in `$db`
$db = new SQLite3(':memory:');
$db->exec("CREATE TABLE users (id INTEGER, name TEXT, email TEXT)");
// Print "Table created with 3 columns" to the output
echo "Table created with 3 columns";
?>
Login to try C/C++/Java/PHP code in the editor
Choosing a Primary Key
A primary key uniquely identifies every row in a table, and an auto-incrementing integer id column (INT AUTO_INCREMENT PRIMARY KEY) is the most common choice -- MySQL assigns each new row the next available number automatically, guaranteeing uniqueness without any extra work.
Example: Choosing a Primary Key
<?php
// Create a new `SQLite3` instance with ':memory:', stored in `$db`
$db = new SQLite3(':memory:');
$db->exec("CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)");
$db->exec("INSERT INTO users (name) VALUES ('Alice')");
// Print `"Auto-assigned id: " . $db->lastInsertRowID()` to the output
echo "Auto-assigned id: " . $db->lastInsertRowID();
?>
Login to try C/C++/Java/PHP code in the editor
Column Constraints: NOT NULL, DEFAULT, UNIQUE
Beyond just a type, a column can carry constraints: NOT NULL requires every row to have a value there, DEFAULT sets an automatic value when none is provided, and UNIQUE ensures no two rows share the same value in that column -- like guaranteeing no two users share an email address.
Example: Column Constraints: NOT NULL, DEFAULT, UNIQUE
<?php
// Create a new `SQLite3` instance with ':memory:', stored in `$db`
$db = new SQLite3(':memory:');
$db->exec("CREATE TABLE users (
id INTEGER PRIMARY KEY,
email TEXT NOT NULL UNIQUE,
role TEXT DEFAULT 'member'
)");
// Print "Constraints applied" to the output
echo "Constraints applied";
?>
Login to try C/C++/Java/PHP code in the editor
Making Table Creation Repeatable
CREATE TABLE IF NOT EXISTS works exactly like its database-level counterpart -- MySQL only creates the table if it does not already exist, silently doing nothing otherwise, which makes a setup script safe to run more than once without erroring.
Example: Making Table Creation Repeatable
<?php
$db = new SQLite3(':memory:');
$db->exec("CREATE TABLE IF NOT EXISTS users (id INTEGER)");
$db->exec("CREATE TABLE IF NOT EXISTS users (id INTEGER)"); // safe to run again
echo "No error on second run";
?>
Login to try C/C++/Java/PHP code in the editor
Verifying a Table's Structure
After creating a table, DESCRIBE tableName (or the equivalent SHOW COLUMNS query) returns each column's name, type, and constraints -- a quick way to confirm from PHP that a table was created exactly as intended.
Example: Verifying a Table's Structure
<?php
$db = new SQLite3(':memory:');
$db->exec("CREATE TABLE users (id INTEGER, name TEXT)");
$result = $db->query("PRAGMA table_info(users)"); // DESCRIBE users; in MySQL
while ($col = $result->fetchArray()) {
echo $col['name'] . "\n";
}
?>
Login to try C/C++/Java/PHP code in the editor
- Forgetting to define a primary key on a new table, making it much harder to reliably update or delete specific rows later.
- Choosing an overly generic column type (like TEXT for everything) instead of an appropriate type (INT, VARCHAR, DATE) that matches the actual data and enables proper validation and indexing.
- Running CREATE TABLE without IF NOT EXISTS in a script that might run more than once, causing an error on the second run.
- CREATE TABLE tableName (column definitions...) defines a new table's structure, run through mysqli_query() like any other SQL statement.
- A primary key column (often an auto-incrementing id) uniquely identifies each row and is essential for reliable updates and deletes.
- IF NOT EXISTS makes table creation safe to re-run without erroring if the table already exists.
CREATE TABLE is standard SQL, and running it through mysqli_query() works identically across all MySQL and MariaDB versions PHP supports.
Chapter Quiz — Complete all 21 topics to unlock
0/21 topics done
Complete these topics first:
- PHP MySQL Introduction
- PHP MySQLi Connection
- PHP PDO Introduction
- PHP CRUD Operations
- PHP Prepared Statements
- PHP Stored Procedures
- PHP Transactions
- PHP Error Handling in DB
- PHP MySQL Connect
- PHP MySQL Create DB
- PHP MySQL Create Table
- PHP MySQL Insert Data
- PHP MySQL Get Last ID
- PHP MySQL Insert Multiple
- PHP MySQL Prepared Statements
- PHP MySQL Select Data
- PHP MySQL Where
- PHP MySQL Order By
- PHP MySQL Delete Data
- PHP MySQL Update Data
- PHP MySQL Limit Data