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
How can we delete an existing MySQL table by using PHP script?
In PHP, you can delete an existing MySQL table using the DROP TABLE SQL statement with PHP's database connection functions. Modern PHP applications should use MySQLi or PDO instead of the deprecated mysql_* functions.
Using MySQLi (Procedural)
Here's how to delete a MySQL table using MySQLi with proper error handling ?
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'password';
$dbname = 'TUTORIALS';
// Create connection
$conn = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
// Check connection
if (!$conn) {
die('Could not connect: ' . mysqli_connect_error());
}
echo 'Connected successfully<br />';
// SQL to drop table
$sql = "DROP TABLE tutorials_tbl";
if (mysqli_query($conn, $sql)) {
echo "Table deleted successfully";
} else {
echo "Error deleting table: " . mysqli_error($conn);
}
// Close connection
mysqli_close($conn);
?>
Using PDO
PDO provides a more secure and object-oriented approach ?
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'password';
$dbname = 'TUTORIALS';
try {
// Create PDO connection
$pdo = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo 'Connected successfully<br />';
// SQL to drop table
$sql = "DROP TABLE tutorials_tbl";
$pdo->exec($sql);
echo "Table deleted successfully";
} catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
// Connection closes automatically
?>
With Safety Check
It's good practice to check if the table exists before attempting to delete it ?
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'password';
$dbname = 'TUTORIALS';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
if (!$conn) {
die('Could not connect: ' . mysqli_connect_error());
}
// Check if table exists
$sql = "DROP TABLE IF EXISTS tutorials_tbl";
if (mysqli_query($conn, $sql)) {
echo "Table deleted successfully (if it existed)";
} else {
echo "Error: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
Key Points
| Method | Security | Error Handling |
|---|---|---|
| MySQLi | Good | Built-in functions |
| PDO | Excellent | Exception-based |
| mysql_* (deprecated) | Poor | Limited |
Conclusion
Use DROP TABLE with MySQLi or PDO for deleting MySQL tables in PHP. Always include IF EXISTS clause to prevent errors if the table doesn't exist. Avoid deprecated mysql_* functions.
Advertisements
