pTutorial

New way to learn PHP

PHP 5 Create and select database

How to create database

We can use the CREATE DATABASE statement to the mysql_query() function to create the database.

Creating database

CREATE DATABASE dattabase_name;

In below example create the database named dp1

<?php

$db_con = mysql_connect("localhost","root","") or die("Connection fail");
$c_db = "CREATE DATABASE my_db1";
$qu = mysql_query($c_db,$db_con);

if ($qu) 
{
  echo "Database my_db has been created successfully.";
}
 else
 {
  echo "Error creating database: " . mysqli_error($dp);
} 


?>

Output

Database my_db has been created successfully.

The mysql_query function sends the query to the database and return object and store a temporary variable. In this case object store in $qu variable.

Select database

Once a successful connection is established with the MySQL server, a database residing on that server can be selected by using mysql_select_db.

Syntax of mysql_select_db()


mysql_select_dp( database name , query variable );

Example of mysql_select_dp()

mysql_select_dp(test);
  • If more than one database are open, used particular database using mysql_select_dp() function to select required database.

Example

<?php

$host = 'localhost';
$user = 'root';
$password="";
$db_con = mysql_connect($host, $user, $password);
$b=mysql_select_db("my_db1");
if($b)
{
echo "Database selected successfully.";
}
else
{
echo"fail to select";
}
mysql_close();

?>

Output

Database selected successfully.

Note: mysql_select_db() function return false if it does not connect to the database.

Step by step process of creating database using WAMP server

First start your WAMP server that are already install on your system

Now open your and type localhost

Appear following window.


First step of creating database | php tutorial

Click on the myphpadmin


second step of creating database | php tutorial

Now appear phpmyadmin window as follows


third step of creating database | php tutorial

Type user name root and password blank (for convenience)

Now appear this window


Fourth step of creating database | php tutorial

Click on database from upper left corner


fifth step of creating database | php tutorial

Type name and click create button

Database created successfully


Final step of creating database | php tutorial

Now click on database that are created at the left side

Now you are ready to create table

Congratulation you are created database successfully

Check database created or not?

Step for checking database

1. Type localhost in your browser and click phpmyadmin.


check database | php tutorial

2. Now you can see your created database in this list.


check database | php tutorial


QUOTES OF THE DAY

Well-begun is half done.

LIKE ON FACEBOOK

+1 ON GOOGLE

SHARE ON TWITTER