DELETE 语句用于从表中删除记录:
DELETE FROM table_name
WHERE some_column = some_value
请注意 DELETE 语法中的 WHERE 子句:WHERE 子句指定应删除哪一条或多条记录。如果省略 WHERE 子句,所有记录都将被删除!
要了解有关 SQL 的更多信息,请访问我们的SQL教程。
让我们看一下 "MyGuests" 表:
id | firstname | lastname | reg_date | |
---|---|---|---|---|
1 | John | Doe | john@example.com | 2014-10-22 14:26:15 |
2 | Mary | Moe | mary@example.com | 2014-10-23 10:22:30 |
3 | Julie | Dooley | julie@example.com | 2014-10-26 10:48:23 |
以下示例删除"MyGuests"表中id=3的记录:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// sql to delete a record
$sql = "DELETE FROM MyGuests WHERE id=3";
if ($conn->query($sql) === TRUE) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . $conn->error;
}
$conn->close();
?>
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// sql to delete a record
$sql = "DELETE FROM MyGuests WHERE id=3";
if (mysqli_query($conn, $sql)) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// sql to delete a record
$sql = "DELETE FROM MyGuests WHERE id=3";
// use exec() because no results are returned
$conn->exec($sql);
echo "Record deleted successfully";
} catch(PDOException $e) {
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
删除记录后,表将如下所示:
id | firstname | lastname | reg_date | |
---|---|---|---|---|
1 | John | Doe | john@example.com | 2014-10-22 14:26:15 |
2 | Mary | Moe | mary@example.com | 2014-10-23 10:22:30 |
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!