Advertisement

Database Creation in MySQLi using PHP

In the last post we discussed about the MySQL database connectivity in PHP, but there is a situation when the database is not created so in that case first we have to create a database and then insert some tables in that database to save data into it so today in this post, we will see how to create a database in PHP and then create a table in that database using PHP MySQL queries.

We see both objects oriented and procedural way of creating a database in MySQL.

The first thing we need to know that how to create a database, then we will see how to run that query in PHP. So Create Database keywords are used to create a database in MySQL.

“Create Database db_name”;

Above is the simple SQL query that will create a database, now I show how to run this query in PHP.

Create Database in MySQL (object-oriented method):

To create a database first, we need to create and check the connection which we learned in the last post; then we can create a database in MySQL.

1

2

3

4

5

6

7

8

9

<?php

$servername="localhost";

$username="root";

$password=" ";

$db_name="database_name";

$conn=newmysqli($server,$username,$password,$db_name);

?>

Above is the simple code to create the connection which we already covered in the last post and the below code checks whether the connection is established or not?

1

2

3

4

5

6

7

8

9

<?php

if($conn->connect_error){

die("Connection Not Establish: ".$conn->connect_error);

}

echo"Successfully Connected To Database";

?>

Now if we combine the above code and then write code for how to create a database it works fine.

1

2

3

4

5

6

7

8

9

10

11

12

13

<?php

$query="CREATE DATABASE any_db_name";

if($conn->query($query)===TRUE){

echo"Data base was created Successfully ";

}else{

echo"Error in Creation of Database: ".$conn->error;

}

$conn->close();

?>

Create Database in MySQLi (procedural method):

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

<?php

$server="localhost";

$username="root";

$password=" ";

$db_name="database_name"

$conn=mysqli_connect($servername,$username,$password,$db_name);

if(!$conn){

die("Connection Not Establish: ".mysqli_connect_error());

}

echo"Successfully Connected To Database";

$query="CREATE DATABASE any_name_DB";

if(mysqli_query($conn,$query)){

echo"Created Successfully ";

}else{

echo"Error in Query : ".mysqli_error($conn);

}

mysqli_close($conn);

?>

Above are the two methods of creating MySqli Database using PHP they both use slandered SQL query Create database to create the database, then use Object-Oriented method $conn->query($sql) to run the query and Procedural method use mysqli_query($conn,$sql) to run the query.