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.
Discuss this tutorial at forum

List of SQL Tutorials


Scripts
PHP
JavaScript
SQL Tutorial List
SQL (Home)
mysql_affected_rows mysql_change_user mysql_close mysql_connect mysql_create_db mysql_data_seek mysql_db_name mysql_db_query mysql_drop_db mysql_errno mysql_error mysql_fetch_array mysql_fetch_assoc mysql_fetch_field mysql_fetch_lengths mysql_fetch_row mysql_field_flags mysql_field_len mysql_field_name mysql_field_seek mysql_field_table mysql_field_type mysql_free_result mysql_insert_id mysql_list_dbs mysql_list_fields mysql_list_tables mysql_num_fields mysql_num_rows mysql_pconnect mysql_query mysql_result mysql_select_db mysql_tablename
SQL site Map
Knowledge Management
Subscribe
Submit your email address and receive article and product notifications. Your email is safe with us.