PHP provides the following methods to delete data in MySQL tables: DELETE statement: used to delete rows matching conditions from the table. TRUNCATE TABLE statement: used to clear all data in the table, including auto-incremented IDs. Practical example: You can delete users from the database using HTML forms and PHP code. The form submits the user ID, and the PHP code uses a DELETE statement to delete the record matching the ID from the users table.
How to delete data from MySQL tables using PHP
PHP provides a variety of methods to delete data from MySQL tables. This tutorial explains the most common methods and provides a practical example.
Method 1: Use the DELETE statement
The easiest way is to use the DELETE
statement. It is used to delete rows matching specific conditions from the table. The syntax is as follows:
DELETE FROM table_name WHERE condition;
For example, to delete users with id
as 5 from the users
table:
$sql = "DELETE FROM users WHERE id = 5"; $conn->query($sql);
Method 2: Use truncate table
The TRUNCATE TABLE
statement is used to delete all data in the table, including auto-incrementing IDs. The syntax is as follows:
TRUNCATE TABLE table_name;
For example, to clear the users
table:
$sql = "TRUNCATE TABLE users"; $conn->query($sql);
Practical case
Consider the following HTML form:
<form action="delete.php" method="post"> <input type="text" name="id"> <input type="submit" value="Delete"> </form>
In the delete.php
file we can delete the user from the database using the id
entered by the user:
<?php // 建立数据库连接 $conn = new mysqli("localhost", "username", "password", "database"); // 获取用户输入的 id $id = $_POST['id']; // 准备删除语句 $sql = "DELETE FROM users WHERE id = ?"; // 准备预处理语句 $stmt = $conn->prepare($sql); // 绑定参数 $stmt->bind_param("i", $id); // 执行查询 $stmt->execute(); // 关闭预处理语句和数据库连接 $stmt->close(); $conn->close(); // 重定向到列表页面 header("Location: list.php"); ?>
This will remove the user from ## Delete the record with id
from the #users table that enters a value for the user.
The above is the detailed content of How to delete data from MySQL table using PHP?. For more information, please follow other related articles on the PHP Chinese website!