Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Which PHP function is used to delete an existing database?
PHP uses the mysql_query() function to delete a MySQL database. However, this function is deprecated since PHP 5.5.0 and removed in PHP 7.0.0. Modern PHP applications should use mysqli or PDO instead.
Syntax (Legacy)
bool mysql_query( sql, connection );
Parameters
| Parameter | Description |
| sql | Required. SQL query to delete a MySQL database (DROP DATABASE command) |
| connection | Optional. If not specified, the last opened connection by mysql_connect will be used |
Modern Approach Using MySQLi
Here's how to delete a database using the recommended MySQLi extension ?
<?php
$servername = "localhost";
$username = "your_username";
$password = "your_password";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// SQL to delete database
$sql = "DROP DATABASE test_database";
if ($conn->query($sql) === TRUE) {
echo "Database deleted successfully";
} else {
echo "Error deleting database: " . $conn->error;
}
$conn->close();
?>
Using PDO
Alternative approach using PDO (PHP Data Objects) ?
<?php
try {
$pdo = new PDO("mysql:host=localhost", "username", "password");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "DROP DATABASE test_database";
$pdo->exec($sql);
echo "Database deleted successfully";
} catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
?>
Conclusion
While mysql_query() was historically used to delete databases, modern PHP development requires MySQLi or PDO. Always use proper error handling when performing database operations to ensure robust applications.
Advertisements
