Learn How to Connect PHP with MySQL Database and Create Database Table

Learn How to Connect PHP with MySQL Database and Create Database Table

May 10, 2016 0 By Abid

Connect PHP with MySQL Database and Create Database Table

There are three steps to connect PHP with MySQL Database and Create Database Table

Step 1: Establish Database Connection

First of all you have to establish database connection. For this use this query:

mysql_connect("Server name here ","user name","password"); 

If you have set user name and password then replace user name and password else just use this: mysql_connect("localhost","root","")

If you would like to display error message in case of connection failure then store this query in a variable $connect. You can use any name for variable .

<?php
$connect=mysqli_connect("localhost","root","");
if(!$connect)
{
die ("Failed to connect!".mysqli_connect_error());
}
else
{
echo "Connected Successfully!";
}
?>

Connect PHP with MySQL Database and Create Database Table

Step 2: Create MySQL Database using PHP

To create database just use this query “create database DBname”.

<?php
$connect=mysqli_connect("localhost","root","");
if(!$connect)
{
die ("Failed to connect!".mysqli_connect_error());
}
else
{
echo "Connected Successfully!";
}
$db="create database NewDatabase";

if(!$db)
{
echo “Database creation failed!”.mysqli_error($connect);
}
echo “<br>”;
else
{
echo “Database created successfully!”;
}
?>

Create MySQL Database using PHP

Step 3: Create MySQL Database Table using PHP

To create MySQL table store sql query into a php variable. Here I used  “$table”. Now you can display messages on screen.

PHP code and sql query is given below:

<?php
$connection=mysqli_connect("localhost","root"," ","NewDB");
$table="create table Bio(
id int(6) PRIMARY KEY,
fname VARCHAR(30) ,
lname VARCHAR(30)  ,
email VARCHAR(60) ,
age int(6) ,
address VARCHAR(30)
)";
if(mysqli_query($connection,$table))
{
echo "Table created successfully";
}
else
{
echo "Error Creating Table".mysqli_error($connection);
}
mysqli_close($connection);
?>