MySQLi Create Table

MySQLi CREATE TABLE command is used to create a new table into the database. The table creation command requires −

  • Name of the table
  • Names of fields
  • Definitions for each field

Below the syntax of creating a MySQL table into the database:

CREATE TABLE table_name(column_name column_type);

Here, We'll create a table named "tbl_customers" in the database "db_nexladder".

tbl_customers(
        id INT AUTO_INCREMENT,
        first_name VARCHAR(32) NOT NULL,
        last_name VARCHAR(32) NOT NULL,
        primary key(id),
  );

Note:

  • NOT NULL is a field attribute and it is being used because we do not want this field to be NULL.
  • AUTO_INCREMENT tells MySQLi to go ahead and add the next available number to the id field.
  • PRIMARY KEY is used to define a column as primary key. You can use multiple columns separated by comma to define a primary key.
<?php
   $conn  = mysqli_connect('localhost:3306', 'user_name', 'password', 'db_nexladder');
   if(! $conn) {
       die('Could not connect: ' . mysqli_error());
   }
   $sql = "CREATE TABLE tbl_customers(id INT AUTO_INCREMENT, first_name VARCHAR(32) NOT NULL, last_name VARCHAR(32) NOT NULL, PRIMARY KEY (id))";
   if (mysqli_query($conn, $sql)) { 
     echo "Table created successfully";
   } else { 
     echo "Error:". mysqli_error($conn); 
   }
   mysqli_close($conn);
 ?>

Output: Table created successfully

It will look like this:

mysqli create table

Below the following command to see the table created:

mysqli show tables

Below the following command to see the table structure:

mysql describe table