Create Database and Create Table in MySQL using PHP
In this session of PHP, we will create database and table in MySQL using PHP : You can also create it using PHPMyAdmin.
We will use CREATE DATABASE & CREATE TABLE statements to create database and table in MySQL respectively.
mysql_query() : This send a MySQL query.
Syntax : resource mysql_query ( string query [, resource link_identifier])
- query : A SQL query that you want to execute.
- Link_identifier : It is MySQL connection, it is option and if you don’t specify it, the last link opened by mysql_connect() is assumed.
Example :
<?php $user_name = 'root'; $password = ''; $hostname = "localhost"; $con = mysql_connect($hostname, $user_name, $password); if(! $con ) { die("Could not connect: " . mysql_error()); } echo "Connection successful</br> "; //Create Database $query = "CREATE database if not exists Employee"; $d_query = mysql_query($query , $con); If(!$d_query) { die("Could not create database : " . mysql_error()); } echo "Database Created Successfully </br>"; //Create table mysql_select_db('Employee'); $c_query="create table Emp(empId int NOT NULL AUTO_INCREMENT, firstName varchar(30) , lastName varchar(30) , age int , designation varchar(30), salary int, PRIMARY KEY(empId) )"; $d_query=mysql_query($c_query , $con); if(!$d_query) { die("Could not create table: " . mysql_error()); } else { echo "Table Created Successfully</br> "; } mysql_close($con) or die ("Error while closing connection"); echo " Connection Close successful"; ?>
Output :