MySQL Create Tables

MySQL Create Tables


Know about What is table ?

A table is a set of data elements using a model of vertical columns and horizontal rows, the cell being the unit where a row and column intersect.. A table has a specified number of columns, but can have any number of rows.

Create Table using PHP and MySQL

Example (MySQLi Object-oriented)

We have to create a table named "person", with four columns: "id", "firstname", "lastname", "email".

Output :

In this example we created a table "person" with four columns and write sql query.

 CREATE TABLE person(
  id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  firstname VARCHAR(30) NOT NULL,
  lastname VARCHAR(30) NOT NULL,
  email VARCHAR(50));

 

The data types that will be used are :

  1. VARCHAR:Holds a variable length string that can contain letters, numbers, and special characters. The maximum size is specified in parenthesis.
  2. INT :The INTEGER data type accepts numeric values with an implied scale of zero. It stores any integer value between -2147483648 to 2147483647.

After the data type, we specify other optional attributes for each column:

  • NOT NULL - Each row must contain a value for that column, null values are not allowed
  • DEFAULT value - Set a default value that is added when no other value is passed
  • UNSIGNED - Used for number types, limits the stored data to positive numbers and zero
  • AUTO INCREMENT - MySQL automatically increases the value of the field by 1 each time a new record is added
  • PRIMARY KEY - Used to uniquely identify the rows in a table. The column with PRIMARY KEY setting is often an ID number, and is often used with AUTO_INCREMENT.

Example (MySQLi Procedural) :

Output :

Example (PDO) :

output :