PHP Create MySQL Table
A data table has a unique name and consists of rows and columns.
Use MySQLi and PDO to Create MySQL Table
The CREATE TABLE statement is used to create a MySQL table.
Before creating the table, we need to use "use myDB" to select the database to operate on:
use myDB;
We will create a table named "MyGuests" with 5 columns: "id", "firstname", "lastname", "email", and "reg_date":
CREATE
TABLE
MyGuests
(
id
INT
(
6
)
UNSIGNED
AUTO_INCREMENT
PRIMARY
KEY
,
firstname
VARCHAR
(
30
)
NOT
NULL
,
lastname
VARCHAR
(
30
)
NOT
NULL
,
VARCHAR
(
50
)
,
reg_date
TIMESTAMP
)
Notes on the table above:
The data type specifies what kind of data a column can store. For the complete data types, please refer to our Data Types Reference Manual.
After setting the data type, you can specify the following additional options for each column:
- NOT NULL - Each row must contain a value (cannot be empty), null values are not allowed.
- DEFAULT value - Sets a default value
- UNSIGNED - Uses an unsigned numeric type, 0 and positive numbers
- AUTO INCREMENT - Sets the MySQL field value to automatically increment by 1 each time a new record is added
- PRIMARY KEY - Sets the unique identifier for each record in the data table. Usually the column's PRIMARY KEY is set to the ID value, used together with AUTO_INCREMENT.
Each table should have a primary key (this column is the "id" column), and the primary key must contain unique values.
The following example shows how to create a table in PHP:
Example (MySQLi - Object-Oriented)
connect_error ) { die ( " Connection failed: " . $conn -> connect_error ) ; } // use sql to create the data table $sql = " CREATE TABLE MyGuests ( id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, firstname VARCHAR(30) NOT NULL, lastname VARCHAR(30) NOT NULL, email VARCHAR(50), reg_date TIMESTAMP ) " ; if ( $conn -> query ( $sql ) === TRUE ) { echo " Table MyGuests created successfully " ; } else { echo " error creating data table: " . $conn -> error ; } $conn -> close ( ) ; ?>Example (MySQLi - Procedural)
Example (PDO)
setAttribute ( PDO :: ATTR_ERRMODE , PDO :: ERRMODE_EXCEPTION ) ; // use sql to create the data table $sql = " CREATE TABLE MyGuests ( id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, firstname VARCHAR(30) NOT NULL, lastname VARCHAR(30) NOT NULL, email VARCHAR(50), reg_date TIMESTAMP ) " ; // use exec(), no result returned $conn -> exec ( $sql ) ; echo " data table MyGuests created successfully " ; } catch ( PDOException $e ) { echo $sql . "" . $e -> getMessage ( ) ; } $conn = null ; ?>