Creating a table by PHP functions
Creating
a MySQL Table Using MySQLi
Create a database first and after that create tables in this database.
To connect to an existing database pass an extra variable “database
name” while connecting to MySQL.
The CREATE TABLE statement is used to create a table in MySQL.
Example:- table named “employees”, with four columns: “id”, “firstname”,
“lastname” and “email” will be created.
The
data types that will be used are :
1. VARCHAR: store a variable-length string (letters,
numbers, and special characters). The maximum size is specified.
2. INT: store numeric values (any integer value
between -2147483648 to 2147483647).
The
attributes that are used along with data types are:
1. NOT NULL: Each row must contain a value for that
column, null values are not allowed.
2. PRIMARY KEY: Used to uniquely identify the rows in a
table. The column with PRIMARY KEY setting is often an ID number.
1. Creating a table using MySQLi
Object-oriented Procedure
Syntax :
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "newDB";
// checking connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed:
" . $conn->connect_error);
}
// sql code to create table
$sql = "CREATE TABLE employees(
id INT(2) PRIMARY KEY,firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT
NULL, email VARCHAR(50))";
if ($conn->query($sql) === TRUE) {
echo "Table employees
created successfully";
} else {
echo "Error creating
table: " . $conn->error;
}
$conn->close();
?>
Output :
0 Comments