Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Sign In Register

PHP MySQL Create Tables

Creating Tables inside MySQL Database Using PHP

In the previous chapter we've learned how to create a database on MySQL server. Now it's time to create some tables inside the database that will actually hold the data. A table organizes the information into rows and columns.

The SQL CREATE TABLE statement is used to create a table in database.

Let's make a SQL query using the CREATE TABLE statement, after that we will execute this SQL query through passing it to the PHP mysqli_query() function to finally create our table.

/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "", "demo");
// Check connection
if($link === false){
    die("ERROR: Could not connect. " . mysqli_connect_error());
// Attempt create table query execution
$sql = "CREATE TABLE persons(
    first_name VARCHAR(30) NOT NULL,
    last_name VARCHAR(30) NOT NULL,
if(mysqli_query($link, $sql)){
    echo "Table created successfully.";
} else{
    echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
// Close connection

The PHP code in the above example creates a table named persons with four columns idfirst_namelast_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 NULLPRIMARY KEYAUTO_INCREMENT, etc. Constraints define rules regarding the values allowed in columns.

Please check out the tutorial on SQL CREATE TABLE statement for the detailed information about syntax, as well as the data types and constraints available in MySQL database system

Sign In or Register to comment.


| make vanilla clean and light
@ 2016 Your Sitename, All rights reserved. Material Design is a design language developed by Google. Material Design makes more liberal use of grid-based layouts and responsive animations and transitions.
Powered by VanillaForums, Designed by ThemeSteam

Contact us
(800) 3032120

Get In Touch