PHP Create a MySQL Database

PHP Create a MySQL Database


One or more tables comprise a database.

To establish or destroy a MySQL database you require special CREATE capabilities.


Create MySql Database

You must have basic knowledge of SQL query to create a mysql database.

The following queries are used to create a database in mysql:

CREATE DATABASE database_name

The following queries are used to delete a database in mysql:

DROP DATABASE database_name




Create a MySQL Database Using MySQLi and PDO

The CREATE DATABASE command is used for building a MySQL database.

The examples below will establish a database called "myDB" :

Example (MySQLi Object-oriented)

The query() method from mysqli class is used to execute a SQL statement or query.

The query() gets two arguments which is a connection object and a string should contain a sql query.

<?php
// Create connection
$conn = new mysqli("localhost", "username", "password");
// Check connection
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
}
// Create database
$sql = "CREATE DATABASE myDB";
if ($conn->query($sql) === TRUE) {
  echo "Database created successfully";
} else {
  echo "Error creating database: " . $conn->error;
}
// Close connection
$conn->close();
?>

Example (MySQLi Procedural)

The mysqli_query() method used to execute a SQL statement or query.

The mysqli_query() gets two arguments which is a connection object and a string should contain a sql query.

<?php
// Create connection
$conn = new mysqli("localhost", "username", "password");
// Check connection
if (!$conn) {
  die("Connection failed: " . mysqli_connect_error());
}
// Create database
$sql = "CREATE DATABASE myDB";
if (mysqli_query($conn, $sql)) {
  echo "Database created successfully";
} else {
  echo "Error creating database: " . mysqli_error($conn);
}
// Close connection
mysqli_close($conn);
?>

Example (PDO)

The exec() method from PDO class is used to execute a SQL statement and it does not return any results from database.

The exec() takes an argument which is a sql query as string.

<?php
try {
  // Create connection
  $conn = new PDO("mysql:host=localhost", "username", "password");
  // Create database
  $sql = "CREATE DATABASE myDB";
  $conn->exec($sql);
  echo "Database created successfully<br />";
} catch(PDOException $e) {
  echo $sql . "<br />" . $e->getMessage();
}
// Close connection
$conn = null;
?>

Tip :- PDO has a wonderful advantage in that it contains an exception class to handle any difficulties that may arise in our database queries.



You can also search for these topics, php create a mysql database, how to create a database website with php and mysql, how will you create a table in mysql database using php, create a mysql database using mysqli in php, create a mysql database mysqli object-oriented example, create a mysql database mysqli procedural, create a mysql database mysqli pdo.