Home >>MySQL Tutorial >PHP MySQL Create Database

PHP MySQL Create Database


Create Database

The CREATE DATABASE statement is used to create a MySQL database. Create database is used to create a MySQL database. We must add the CREATE DATABASE statement to the mysql_query() function to execute the command. Ex i(Create database)
<?php
 $con = mysql_connect("localhost","root","") or die(mysql_error());
	// Check connection
	if (mysql_connect_errno($con))
	  {
	  echo "Failed to connect to MySQL: " .mysql_connect_error($con);
	  }
	// Create database
	$sql="CREATE DATABASE Employee";
	if (mysql_query($con,$sql))
	  {
	 echo "Database Employee created successfully";
	  }
	else
	  {
	 echo "Error creating database: " .mysql_error();
  }
?>
In the above example first we create the connection with the database then we write statement to create a database of name employee after that this statement is passed to mysql_query() along with the connection variable of the database.

Create a table

The CREATE TABLE statement is used to create a table Create table is used to create a table. while creating a table we can define several constraints such as primary key, unique key,auto_increment etc. We must add the CREATE TABLE statement to the mysql_query() function to execute the command. Ex (Create Table)
<?php
	$con=mysql_connect("localhost","root","") or die(mysql_error());
	
	// select database 
	mysql_select_db("Employee",$con);
	  
	// Create table
	
	$sql="CREATE TABLE empInfo
		(
		emp_id int auto_increment primary key,
		name char(50) not null,
		email varchar(50) not null,
		mobile bigint not null
		)";
	if (mysql_query($sql))
	  {
	  echo "Table empInfo created successfully";
	  }
	else
	  {
	 echo  "Error creating database: " .mysql_error();
  }
?>
In the above example first we create the connection with the database then we select a database of name employee then we write the statement to create a table,and this statement is passed to mysql_query().

Popular Tutorials