In PHP development, deleting database tables is a common operation. Sometimes it is necessary to delete some unused tables during the development process, so how to use PHP to complete this operation? This article will introduce how to use PHP to delete the tables corresponding to the database.
1. Use the DROP statement to delete the database table
In MySQL, you can use the DROP statement to delete the database table. PHP can achieve this function through the MySQLi extension. The following is the sample code:
<?php $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "myDB"; // 创建连接 $conn = mysqli_connect($servername, $username, $password, $dbname); // 检测连接是否成功 if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } $sql = "DROP TABLE my_table";//删除my_table表 if (mysqli_query($conn, $sql)) { echo "Table my_table deleted successfully"; } else { echo "Error deleting table: " . mysqli_error($conn); } mysqli_close($conn);//关闭连接 ?>
When this PHP file is executed, the database table named my_table will be deleted. If the deletion is successful, "Table my_table deleted successfully" will be output; otherwise, "Error deleting table" will be output.
2. Use PDO to delete database tables
PDO is another common PHP extension that can also be used to delete database tables. The following is the sample code:
<?php $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "myDB"; try { $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password); // 设置 PDO 错误模式为异常 $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $sql = "DROP TABLE my_table";//删除my_table表 // 使用 exec(),因为没有结果返回 $conn->exec($sql); echo "Table my_table deleted successfully"; } catch(PDOException $e) { echo $sql . "<br>" . $e->getMessage(); } $conn = null;//关闭连接 ?>
When this PHP file is executed, the database table named my_table will also be deleted. If the deletion is successful, "Table my_table deleted successfully" will be output; otherwise, an error message will be output.
In short, operating the database with PHP can be very simple and convenient. Deleting a database table is one of the common operations, and this function can be easily achieved using the above code. However, it should be noted that deleting the database table will delete the data in the table together, so you need to operate with caution in important situations.
The above is the detailed content of How to delete the table corresponding to the database in php. For more information, please follow other related articles on the PHP Chinese website!