How to create table in MySQL Database using php

How to create table in MySQL Database using php


In this tutorial, you will be learning how to create a table in MySQL Database (phpMyAdmin) with sql command using PHP Script.

First, You have to create a database in server (phpMyAdmin). Now guys, let's write the command to create mysql table in database named as posts

Example (MySQLi Object-Oriented)
<?php
    $host = "localhost";
    $username = "your_username";
    $password = "your_password";
    $database = "your_database_name";

    // Create DB Connection
    $conn = new mysqli($host, $username, $password, $database);

    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }

    // SQL Command to Create Table
    $query = "CREATE TABLE posts (
        id int NOT NULL AUTO_INCREMENT,
        title varchar(191),
        sub_title varchar(191),
        description TEXT,
        PRIMARY KEY (id)
    )";

    if ($conn->query($query) === TRUE)
    {
        echo "Table posts created successfully";
    }
    else
    {
        echo "Error creating table: " . $conn->error;
    }

    $conn->close();
?>


Example in (MySQLi Procedural)
<?php
    $host = "localhost";
    $username = "your_username";
    $password = "your_password";
    $database = "your_database_name";

    // Create DB Connection
    $conn = mysqli_connect($host, $username, $password, $database);

    // Check connection
    if (!$conn) {
        die("Connection failed: " . mysqli_connect_error());
    }

    // SQL Command to Create Table
    $query = "CREATE TABLE posts (
        id int NOT NULL AUTO_INCREMENT,
        title varchar(191),
        sub_title varchar(191),
        description TEXT,
        PRIMARY KEY (id)
    )";

    if (mysqli_query($conn, $query))
    {
        echo "Table posts created successfully";
    }
    else
    {
        echo "Error creating table: " . mysqli_error($conn);
    }

    mysqli_close($conn);

?>



Thanks for reading...