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.