MySQLi Create Table using PHP
The CREATE TABLE statement is used to create a table, while creating a table we can define several constraints such as primary key, unique key,auto_increment, etc. We must add the CREATE TABLE statement to the mysqli_query() function to execute the command.
Ex (Create Table):
Syntax
create table users(
id INT AUTO_INCREMENT,
name VARCHAR(20) NOT NULL,
salary INT NOT NULL,
primary key (id)
)
MySQLi Table Detail
The data type specifies what type of data the column can hold. For a complete reference of all the available data types, go to our Data Types reference.
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 - MySQLi 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 the PRIMARY KEY setting is often an ID number and is often used with AUTO_INCREMENT
<?php
$db=mysqli_connect("localhost","root","","users") or die(mysqli_error());
// Create table
$sql="CREATE TABLE users(
id INT AUTO_INCREMENT,
name VARCHAR(20) NOT NULL,
salary INT NOT NULL,
primary key (id)
)";
if (mysqli_query($db,$sql)){
echo "Table user created successfully";
}else{
echo "Error creating database: " .mysqli_error($db);
}
?>
Output:
Table users created successfully
Series:
MySql Tutorials Hub
