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
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
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()
- 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
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.
.png)
Click on the myphpadmin
.png)
Now appear phpmyadmin window as follows
.png)
Type user name root and password blank (for convenience)
Now appear this window
.png)
Click on database from upper left corner
.png)
Type name and click create button
Database created successfully
.png)
Now click on database that are created at the left side
Now you are ready to create table
Congratulation you are created database successfully