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.


<?php /* 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( 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: Could not able to execute $sql. " . mysqli_error($link); } // Close connection mysqli_close($link); ?>

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.