CREATE DATABASE <new_db>
To use PHP PDO we will work like this.
require "config.php"; // Database connection string
$dbo->exec("Create database newdb");
WE must be interested to know success of the query and same time to display error message in case of failure. Here is the code for that.
<?Php
require "config.php"; // Database connection string
if($dbo->exec("Create database newdb2")){
echo 'New Database created';
}else{print_r($dbo->errorInfo());
}
?>
<?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 ());
}?>
<?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.
Gurjit Singh | 24-03-2009 |
I think this is a best code which resolved my problem of database creation using php 5 |
omar | 21-07-2009 |
thanks.. that really helped. i was using the old function and wasnt able to create:) |
Abi afif | 13-07-2010 |
Thanks you, that really helped.... |
simbhu | 04-08-2010 |
how do i know server name and user name in single windows system. |
Ajay | 20-04-2012 |
Thanks dude. |