Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

PHP MySQL Create Table

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

,

email

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:

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 ; ?>