By using PHP PDO we can create database in MySQL. To create database we must have required privilege in our database connection. Here is the query to create database.
This old MySQL extension was deprecated in PHP 4.3.0 and was removed in PHP 7
Use CREATE DATABASE query in place of mysql_create_db().
We can create database in mysql server by using mysql_create_db function. If sufficient permission is there for the user then this function will create the database in MySQL Server. Let us try with this simple example for creating a database.
<?php
// hostname or ip of server
$servername='localhost';
// username and password
$dbusername='username';
$dbpassword='password';
$link=mysql_connect ("$servername","$dbusername","$dbpassword")
or die ( " Not able to connect to server ");
if (mysql_create_db ("new_db")) {
print ("Database created successfully <br>");
} else {
print ("Error creating database: <br><br>". mysql_error ());
}?>
The above code will create a new database new_db in our MySQL server.
PHP5 and above
The function mysql_create_db() is not supported by PHP 5. We have to use sql command to create a database in PHP 5. Here is the code to create database in PHP 5
<?php
// hostname or ip of server
$servername='localhost';
// username and password to log onto db server
$dbusername='userid';
$dbpassword='password';
$link=mysql_connect ("$servername","$dbusername","$dbpassword")
or die ( " Not able to connect to server ");
$query="CREATE DATABASE IF NOT EXISTS new_db";
if (mysql_query("$query")) {
print ("Database created successfully <br>");
} else {
print ("Error in creating database: <br><br>". mysql_error ());
}
?>
The above code will create database in PHP 5. Note that inside the query to create database we have used IF NOT EXISTS , so there will not be any error message if database is already exist and we are trying to create with same name. Without the clause IF NOT EXISTS we will get error message if we try to create a database which is already exists.
This article is written by plus2net.com team.
https://www.plus2net.com