Header Ads

PHP Create MySQL Tables

A database table has its own unique name and consists of columns and rows.


Create a MySQL Table Using MySQL:

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

We will create a table named "Student", with five columns: "id", "name", "lastname", "rollno" and "admsn_date":

CREATE TABLE Student(
id INT(10) AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
rollno VARCHAR(50),
admsn_date TIMESTAMP
)

After the data type, you can 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
Each table should have a primary key column (in this case: the "id" column). Its value must be unique for each record in the table.

The following examples shows how to create the table in PHP:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "data";

// Create connection$conn = new mysqli($servername, $username, $password, $dbname);
// Check connectionif ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

// sql to create table$sql = "CREATE TABLE Student(
id INT(10) AUTO_INCREMENT PRIMARY KEY, 
name VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
rollno VARCHAR(50),
admsn_date TIMESTAMP
)"
;

if ($conn->query($sql) === TRUE) {
    echo "Table MyGuests created successfully";
else {
    echo "Error creating table: " . $conn->error;
}

$conn->close();
?>


No comments

Powered by Blogger.