Ask Question

Menu

How to create table in MySQL using php script


For create table in MySQL the CREATE TABLE statement is used.Before run the script for create table in MySQL first create a database in MySQL.

The following example is about how to create a table in mysql without open the phpmyadmin or MySQL.

Example (MySQLi Object-oriented)

<?php
$servername = "localhost";
$username = "root";
$password = "";// Put your password
$dbname = "admin";// Put your database name
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// sql to create table
$sql = "CREATE TABLE Student
(
ID int NOT NULL AUTO_INCREMENT,
FirstName varchar(50),
LastName varchar(50),
RollNo varchar(50),
City varchar(50),
PRIMARY KEY (ID)
)";
if ($conn->query($sql) === TRUE) {
echo "Table test created successfully";
}
else {
echo "Error creating table: " . $conn->error;
}
$conn->close();
?>

Example (MySQLi Procedural)

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "admin";//put your database name here
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// sql query to create table
$sql = "CREATE TABLE Student
(
ID int NOT NULL AUTO_INCREMENT,
LastName varchar(50),
FirstName varchar(50),
RollNo varchar(50),
City varchar(50),
PRIMARY KEY (ID)
);
if (mysqli_query($conn, $sql)) {
echo "Table test created successfully";
}
else {
echo "Error creating table: " . mysqli_error($conn);
}
mysqli_close($conn);
?>






Subscribe with us to get latest topic update






Choose a Language



Subscribe