PHP MySQL 删除数据
使用 MySQLi 和 PDO 从 MySQL 表中删除数据
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 | [email protected] | 2014-10-22 14:26:15 |
2 | Mary | Moe | [email protected] | 2014-10-23 10:22:30 |
3 | Julie | Dooley | [email protected] | 2014-10-26 10:48:23 |
以下示例将删除 "MyGuests" 表中 id=3 的记录
示例 (MySQLi 面向对象)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// 创建连接
$conn = new mysqli($servername, $username, $password, $dbname);
// 检查连接
if ($conn->connect_error) {
die("连接失败: " . $conn->connect_error);
}
// 删除记录的 sql 语句
$sql = "DELETE FROM MyGuests WHERE id=3";
if ($conn->query($sql) === TRUE) {
echo "记录删除成功";
} else {
echo "删除记录时出错: " . $conn->error;
}
$conn->close();
?>
示例 (MySQLi 过程化)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// 创建连接
$conn = mysqli_connect($servername, $username, $password, $dbname);
// 检查连接
if (!$conn) {
die("连接失败: " . mysqli_connect_error());
}
// 删除记录的 sql 语句
$sql = "DELETE FROM MyGuests WHERE id=3";
if (mysqli_query($conn, $sql)) {
echo "记录删除成功";
} else {
echo "删除记录时出错: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
示例 (PDO)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// 将 PDO 错误模式设置为异常
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// 删除记录的 sql 语句
$sql = "DELETE FROM MyGuests WHERE id=3";
// 使用 exec() 因为没有返回结果
$conn->exec($sql);
echo "记录删除成功";
} catch(PDOException $e) {
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
删除记录后,表将如下所示
id | firstname | lastname | reg_date | |
---|---|---|---|---|
1 | John | Doe | [email protected] | 2014-10-22 14:26:15 |
2 | Mary | Moe | [email protected] | 2014-10-23 10:22:30 |