PHP & MySQL: Creating a Database

A database is a place where multiple tables are existed. These tables are known as objects. A database can be created easily by using PHP and MySQL. To create a database, CREATE DATABASE database_name command is used. This page describes the process of creating a database from the PHP file by using MySQL.

Creating a Database

To create a database create database command is used. The syntax of database creation is given below:

CREATE DATABASE database_name

Here, database_name = name of the database.

For executing CREATE DATABASE statement, mysql_query() function is used. mysql_query() function sends a query to MySQL connection. Without it, it's not possible to send query to MySQL connection.

Example of creating a database

Let, we want to create a database named as my_db. Now the sample code for creating the database will look like the followings:

<?php
    $my_con = mysql_connect("localhost","root","");
    
    if (!$my_con){
          die('Connection failed: ' . mysql_error());
    }

    if (mysql_query("CREATE DATABASE my_db",$my_con)){
          echo "Database created successfully...";
    }
    
    else  {
          echo "Error while creating the database: " . mysql_error();
    }

    mysql_close($my_con);
?>

After the database my_db is created successfully, Database created successfully... message will be show on your browser page.

Discussion of the above code segment

Here, $my_con variable is used to connect with MySQL. Later, CREATE DATABASE command is used to create database. If the database is created successfully, Database created successfully... message will be shown. Otherwise, Error while creating the database: message will be displayed.

© Written by rancidTaste

If you are enjoyed this post, please consider to give a thumbs up and leave a comment. You may Subscribe to rancidTaste's RSS feed to get new pages which will be delivered to your feed reader. You can also read more hubs by rancidTaste.

Want to express your knowledge and ideas, click here to join Hubpages.

It's simple, just like 1-2-3

More by this Author


Comments

No comments yet.

    Sign in or sign up and post using a HubPages Network account.

    0 of 8192 characters used
    Post Comment

    No HTML is allowed in comments, but URLs will be hyperlinked. Comments are not for promoting your articles or other sites.


    Click to Rate This Article
    working