PHP Tutorial PHP Advanced PHP References

Delete MySQL Database using PHP



A database consists of one or more tables. To create or to delete a MySQL database, appropriate privilege is required. Take extra measures while dropping a database. Deleting a database will result in loss of complete information stored in the database.

The DROP DATABASE statement is used to delete a database in MySQL. For example, to delete a database named "myDatabase", the following query can be used:

DROP DATABASE myDatabase

Along with this, to connect to the MySQL server, mysqli_connect() function can be used. After establishing the connection, mysqli_query() function can be used to perform the query to delete the given database.

Delete a MySQL Database - Object-oriented style

The example below demonstrates how to delete a database named "myDatabase" in object-oriented style.

<?php
$servername = "localhost";
$username = "username";
$password = "password";

//establishing connection 
$mysqli = new mysqli($servername, $username, $password);

//checking connection
if ($mysqli->connect_errno) {
  echo "Failed to connect to MySQL: ". $mysqli->connect_error;
  exit();
}

//query for deleting database
$sql = "DROP DATABASE myDatabase";

//executing the query
if (!$mysqli->query($sql)) {
  echo "Error deleting database: ". $mysqli->error;
} else { 
  echo "myDatabase deleted successfully.";
}

//closing the connection
$mysqli->close();
?>

Delete a MySQL Database - Procedural style

To obtain the same result using procedural style, the following script can be used.

<?php
$servername = "localhost";
$username = "username";
$password = "password";

//establishing connection 
$mysqli = mysqli_connect($servername, $username, $password);

//checking connection
if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: ". mysqli_connect_error();
  exit();
}

//query for deleting database
$sql = "DROP DATABASE myDatabase";

//executing the query
if (!mysqli_query($mysqli, $sql)) {
  echo "Error deleting database: ". mysqli_error($mysqli);
} else { 
  echo "myDatabase deleted successfully.";
}

//closing the connection
mysqli_close($mysqli);
?>

Complete PHP MySQLi Reference

For a complete reference of all properties, methods and functions of PHP MySQLi extension, see PHP MySQLi Reference.


❮ PHP & MySQL