Create MySQL database in PHP

MySQL Create Database: mysql_query()

This section is just for the completeness of the tutorial. In actual scenario, the use of phpmyadmin is recommended. Phpmyadmin frees you from the burden of writing scripts for creating a mysql database.

Here, Following the Common Steps to execute any SQL statements in PHP, we define a string variable “$sql_statement” which contains the actual SQL statement to create a database. This is explained as below.
$sql_statement = “Create database user”;

To create a database using dynamic query the following SQL statement can be used.

$sql_statement = “Create database ”.$dbname;

After this, we execute this query using the PHP inbuilt function mysql_query() as explained below.>
mysql_query ($sql_statement, $conn);

As explained earlier, $conn is the database connection string retrieved using the mysql_connect() function.

Hence the complete code to crate a mysql database would be as below.

$conn = mysql_connect ("host","userid", "password");
$sql_statement = “Create database user”;
mysql_query($sql_statement,$conn) or die(“Could not create database”);

After the execution this SQL statement, a database named “user” will be created.


Example to create a MySQL Database

This source code creates a webform. The user is allowed to enter the name of the database he wishes to create. This web form is processed and the database is created. Error is thrown if anything goes wrong. The name of this file is "create_database.php" Try it yourself!

<?php
//Retrieve the database name
$database = $_GET["db"];
//Continue if database name is non blank
if($database!="")
{
//Prepare the SQL Statement
$sql_statement = "Create database ".$database;

//Connect to the MySQL Database
$conn = mysql_connect ("host","userid", "password");

//Create the database
mysql_query($sql_statement,$conn)
or die("Could not create database");
echo "Database ".." created successfully";
}
?>
<html>
<head>
<title>Create A Database</title>
</head>
<body>
<form action="create_database.php">
<table align=center>
<tr><td>Database Name:</td><td><input type=text name=db></td></tr>
<tr align=center><td colspan=2><input type=submit value=Submit></td></tr>
</form>
</body>
</html>