PHP MySQL Create Table in Database



In the previous example, we have created a database in PHP using MySQL. In this source code example, we will see how to create a database table in PHP using MySQLi.

PHP MySQL Create Table in Database

Before creating a table, you first need to create a database. Use this tutorial to create a database in PHP.

Here is a PHP script that creates a database table in MySQL server:

<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */

$host= "localhost";
$username= "root";
$password = "";

$db_name = "demo_db";

$mysql_connection = mysqli_connect($host, $username, $password, $db_name);
 
// Check connection
if ($mysql_connection->connect_errno) {
    printf("connection failed: %s\n", $mysql_connection->connect_error());
    exit();
}
 
// Attempt create table query execution
$sql = "CREATE TABLE students(
    id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
    first_name VARCHAR(255) NOT NULL,
    last_name VARCHAR(255) NOT NULL,
    email VARCHAR(255) NOT NULL UNIQUE
)";
if(mysqli_query($mysql_connection, $sql)){
    echo "Table created successfully.";
} else{
    echo "ERROR: Could not able to execute $sql. " . mysqli_error($mysql_connection);
}
 
// Close connection
mysqli_close($mysql_connection);
?>
Let's understand the above PHP script.

The mysqli_connect() function opens a new connection to the MySQL server:
$host= "localhost";
$username= "root";
$password = "";

$db_name = "demo_db";

$mysql_connection = mysqli_connect($host, $username, $password, $db_name);

SQL query for creating a database table:

// Attempt create table query execution
$sql = "CREATE TABLE students(
    id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
    first_name VARCHAR(255) NOT NULL,
    last_name VARCHAR(255) NOT NULL,
    email VARCHAR(255) NOT NULL UNIQUE
)";

The mysqli_query() function performs a query against a database:

if(mysqli_query($mysql_connection, $sql)){
    echo "Table created successfully.";
} else{
    echo "ERROR: Could not able to execute $sql. " . mysqli_error($mysql_connection);
}

Closing MySQL server connection:

// Close connection
mysqli_close($mysql_connection);

Comments