{Quality Online Education Since 2009}


MySQL Create Database and Tables

Advertisement

MySQL CREATE is used to create Database and its Tables.

Create a Database

CREATE DATABASE statement is used to create a database in MySQL.

We have to add the CREATE DATABASE statement to the mysqli_query() function to execute the command.

Example:
<?php
// Database connection establishment
    $con=mysqli_connect("example.com","alex","qwerty");
    
// Check connection
    if (mysqli_connect_errno($con)) {
    echo "MySQL database connection failed: " . mysqli_connect_error();
    }

// Create database
    if (mysqli_query($con,"CREATE DATABASE my_database")) {
        echo "Database created successfully";
    }else {
        echo "Error in creating database: " . mysqli_error($con);
    }
?>  

Create a Table in Database

CREATE TABLE statement is used to create a table in MySQL database.

We have to add the CREATE TABLE statement to the mysqli_query() function to execute the command.

Example:
<?php
// Database connection establishment
    $con=mysqli_connect("example.com","alex","qwerty","my_database");
    
// Check connection
    if (mysqli_connect_errno($con)) {
    echo "MySQL database connection failed: " . mysqli_connect_error();
    }

// Create table query 
    $query = "CREATE TABLE users(
     id INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
     name VARCHAR( 25 ) NOT NULL ,
     last_name VARCHAR( 25 ) NOT NULL ,
     age INT NOT NULL 
     )";

// Execute query
    if (mysqli_query($con,$query)) {
        echo "Table created successfully";
    }else {
        echo "Error in creating table: " . mysqli_error($con);
    }
?>  


« Previous Chapter
DDL, DML and DCL
Next Chapter »
MySQL INSERT INTO