刪除 MySQL 資料表使用 DROP TABLE 命令,操作簡單但不可逆,執行前務必確認並備份重要資料。本文說明語法、命令列操作流程,以及 PHP 腳本整合範例。
DROP TABLE table_name;
root@host# mysql -u root -p Enter password:******* mysql> use TUTORIALS; Database changed mysql> DROP TABLE tutorials_tbl; Query OK, 0 rows affected (0.8 sec) mysql>
透過 mysql_query() 執行 DROP TABLE,並檢查回傳值判斷成敗:
<html>
<head>
<title>Deleting MySQL Tables</title>
</head>
<body>
<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully<br />';
$sql = "DROP TABLE tutorials_tbl";
mysql_select_db('TUTORIALS');
$retval = mysql_query($sql, $conn);
if(! $retval ) {
die('Could not delete table: ' . mysql_error());
}
echo "Table deleted successfully\n";
mysql_close($conn);
?>
</body>
</html>
警示:DROP TABLE 會永久移除表結構與所有資料,無法透過 ROLLBACK 復原。生產環境執行前請三思,並確保有完整備份策略。