PHP : MySQL Create Table

Data is stored in the form of tables in the database. A table has its own unique name and consists of rows and columns.

Syntax:

CREATE TABLE table_name (column_name column_type);

Create Table using PHP and MySQL

Here, first we will create database connection, and then we will run mysql query to create table on connection object.

<?php
/**
 * Create Database Table
 */
 
/**
 * Create Database Connection
 */
 
$database_server = 'localhost';
$database_username = 'root';
$database_password = '';
$database_name = 'student';
 
// Create connection using mysqli_connect()
$conn = mysqli_connect($database_server, $database_username, $database_password, $database_name);
 
// If $conn is false, connection is failed
if (!$conn ) {
  die("Failed to connect to MySQL: " . mysqli_connect_error());
}
 
// Mysql query to create table
$sql_query = "CREATE TABLE users (
	id INT(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
	name VARCHAR(30) NOT NULL,
	mobile VARCHAR(10) NOT NULL,
	email VARCHAR(50) NOT NULL UNIQUE
)";

$status = $conn->query($sql_query);
 
// If tables created, status should be true
if ($status) {
	echo "Table users created successfully.";
}
else {
	echo "Error creating table: " . $conn->error;
}
 
// Connection Close
$conn->close();
?>

Description:

  • First create a database connection and store it in $conn object.
  • Then, assign database query to a variable and pass it to query() function in above object.
  • If query returns true, it means that tables has been created, otherwise there will be some error.
  • database connection can be closed at the end.


Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.