In this article I will show you, how to create database and tables within MySQl database in PHP.

Creating Database:

CREATE DATABASE statement is used to creating database in MySQL database server.

Syntax:

CREATE  DATABASE  DATABASE_NAME

Example:
<?php
 
    // creatingconnection with mysql database server
 
    $con = mysql_connect("localhost", "root", "root");
    // check connection is establish or not
    if(!$con)
    {
        die ("Connectionnot established! Please try again");
    }
 
    echo '<b>Connection successfully open</b>'.'</br>';
 
    // Creating database
        $qry = "CREATE DATABASE TempDatabase";
    // Executing query in MySql database server
    if(mysql_query($qry,$con))
    {
        echo 'Database successfully created.'.'</br>';
    }
    else
    {
        echo 'Database creation failed ! ';
    }
 
    //Closing the connection
    mysql_close($con);
    echo '<b>Connection closed successfully</b>';
?>
Output:

Creating Database and Table’s in MySQL

Creating Table:

CREATE TABLE statement is used for creating table in MySQL database server.

Syntax:
CREATETABLE Table_Name
 (
      column_name1  data_type,
      column_name2data_type,
      ......................
      ......................
 
      column_nameNdata_type
 )

 

Example: Creating table in specified database
<?php
 
    // creatingconnection with mysql database server
 
    $con = mysql_connect("localhost", "root", "root");
    // check connection is establish or not
    if(!$con)
    {
        die ("Connectionnot established! Please try again");
    }
 
    //Selecting databse
    mysql_select_db("TempDatabase",$con);
    // Creatingtable in above selecting database
        $qry ="CREATE TABLE tblTemp
                (
                  Id int,
                  Username varchar(50),
                  EmailId  varchar(60),
                  Address varchar(100),
                  MobileNo varchar(20)  
                 )";
    // Executingquery in MySql database server
    if(mysql_query($qry,$con))
    {
        echo 'Table successfully created.'.'</br>';
    }
    else
    {
        echo 'Table creation failed ! ';
    }
 
    //Closingthe connection
    mysql_close($con);
 
?>

 

Note: A database must be selected before a table can be created. The database is selected with the mysql_select_db() function. When you create a table field of type varchar, you must specify the maximum length of the field, e.g. varchar(50).

Output:

Creating Database and Table’s in MySQL


  Modified On Nov-30-2017 12:59:03 AM

Leave Comment