PHP Tutorial
Home
PHP Install Xampp
PHP Syntax & Comments
PHP Variables
PHP Constants
PHP Data Types
PHP Echo & Print
PHP Strings
PHP If...Else...Elseif
PHP Ternary Operator
PHP Loops
PHP Functions
PHP Arrays
PHP GET & POST
PHP Advanced
PHP Date and Time
PHP Include and Require
PHP File Upload
PHP Sessions
PHP Cookies
PHP Send Email
PHP JSON Parsing
PHP MySQL Database
PHP MySQL Introduction
PHP Connect to MySQL
PHP MySQL Create DB
PHP MySQL Create Table
PHP MySQL Insert Data
PHP MySQL Select Data
PHP MySQL Delete Data
PHP MySQL Update Data
PHP MySQL Where
Create a MySQL Table Using MySQLi
CREATE TABLE statement is used to create a table in MySQL.
The below examples shows how to create the table in PHP.
Example : MySQLi Procedural
<?php // Create connection $link = mysqli_connect("localhost", "root", "password", "demo"); // Check connection if (!$link) { die("Connection failed: " . mysqli_connect_error()); } // sql to create table $sql = "CREATE TABLE user( id INT NOT NULL PRIMARY KEY AUTO_INCREMENT, first_name VARCHAR(30) NOT NULL, last_name VARCHAR(30) NOT NULL, email VARCHAR(70) NOT NULL UNIQUE )"; if (mysqli_query($link, $sql)) { echo "Table created successfully"; } else { echo "Error creating table: " . mysqli_error($link); } ?>
The PHP code in the above example creates a table named user with four columns id, first_name, last_name and email inside the demo database.
Notice that each field name is followed by a data type declaration; this declaration specifies what type of data the column can hold, whether integer, string, date, etc.
There are a few additional constraints (also called modifiers) that are specified after the column name in the preceding SQL statement, like NOT NULL, PRIMARY KEY, AUTO_INCREMENT, etc. The constraints define rules regarding the values allowed in columns.