MySQL 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 mysql_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)
)
Mysql 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 - 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 the PRIMARY KEY setting is often an ID number and is often used with AUTO_INCREMENT
<?php
$db=mysql_connect("localhost","root","") or die(mysql_error());
// select database
mysql_select_db("users",$db);
// Create table
$sql="CREATE TABLE users(
id INT AUTO_INCREMENT,
name VARCHAR(20) NOT NULL,
salary INT NOT NULL,
primary key (id)
)";
if (mysql_query($sql)){
echo "Table user created successfully";
}else{
echo "Error creating database: " .mysql_error();
}
?>
Output:
Table users created successfully
Series:
MySql Tutorials Hub
