MySQL Drop Table
Dropping a table in MySQL is very easy, but you must be very careful when performing a drop table operation, because after executing the drop command, all data will disappear.
Syntax
The following is the general syntax for dropping a MySQL table:
DROP TABLE table_name; -- 直接删除表,不检查是否存在
or
DROP TABLE [IF EXISTS] table_name; -- 会检查是否存在,如果存在则删除
Parameter Description:
table_nameis the name of the table to drop.IF EXISTSis an optional clause indicating that the drop operation is performed only if the table exists, avoiding errors caused by a non-existent table.
-- 删除表,如果存在的话
DROP TABLE IF EXISTS mytable;
-- Drop table directly, without checking existence
DROP TABLE mytable;
Please replace mytable with the name of the table you want to drop.
If you only want to delete all data in a table but keep the table structure, you can use the TRUNCATE TABLE statement:
TRUNCATE TABLE table_name;
This empties all data in the table but does not drop the table itself.
Notes:
- Back up data: Before dropping a table, make sure the data has been backed up, if you need it.
- Foreign key constraint: If the table has foreign key constraints with other tables, you may need to drop the foreign key constraints first, or make sure the dependencies are handled properly.
Example
The following example drops the table runoob_tbl:
Example
root@host# mysql
u root
p
Enter password:
mysql
USE
RUNOOB;
DATABASE
changed
mysql
DROP
TABLE
runoob_tbl;
Query OK
,
0
ROWS
affected
(
0.8
sec
)
mysql
Dropping a Table with a PHP Script
PHP uses the mysqli_query function to drop a MySQL table.
This function takes two parameters and returns TRUE on success, or FALSE otherwise.
Syntax
mysqli_query(connection,query,resultmode);
| Parameters | Description |
|---|---|
| connection | Required. Specifies the MySQL connection to use. |
| query | Required, specifies the query string. |
| resultmode |
Optional. A constant. Can be any of the following values: |
Example
The following example uses a PHP script to drop the table runoob_tbl:
Drop the database
' ; $sql = " DROP TABLE runoob_tbl " ; mysqli_select_db ( $conn , ' RUNOOB ' ) ; $retval = mysqli_query ( $conn , $sql ) ; if ( ! $retval ) { die ( ' Failed to drop table: ' . mysqli_error ( $conn ) ) ; } echo " Table dropped successfully \n " ; mysqli_close ( $conn ) ; ?>After successful execution, if we use the following command, we will no longer see the runoob_tbl table:
mysql> show tables;
Empty set (0.01 sec)