SQL PHP HTML ASP JavaScript articles and free scripts to download
 

PHP MySQL Creating Database


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.

Gurjit Singh24-03-2009
I think this is a best code which resolved my problem of database creation using php 5
omar21-07-2009
thanks.. that really helped. i was using the old function and wasnt able to create:)
Abi afif13-07-2010
Thanks you, that really helped....
simbhu04-08-2010
how do i know server name and user name in single windows system.
Post Comment This is for short comments only. Use the forum for more discussions.
Name
Email( not to be displayed)Privacy Policy
1+2=This is to prevent automatic submission by spammers. Please enter the result of the sum as asked
Sections
PHP
JavaScript
ASP
HTML
SQL
Photoshop
Articles SEO
SQL Tutorial List
SQL site Map
Knowledge Management
Subscribe
Submit your email address and receive article and product notifications. Your email is safe with us.