W3C中文教程
全球最大最新的中文 Web 技术教程
HTML CSS SQL PHP COLORS MYSQL BOOTSTRAP
 

PHP MySQL 删除数据



使用 MySQLi 和 PDO 从数据表中删除数据

DELETE 语句用于从数据库表中删除行。

DELETE FROM table_name
WHERE some_column = some_value
Note 请注意 DELETE 语法中的 WHERE 子句: WHERE 子句规定了哪些记录需要删除。如果您想省去 WHERE 子句,所有的记录都会被删除!

如需学习更多关于 SQL 的知识,请访问我们的 SQL 教程

让我们来看看 "MyGuests" 表:

id firstname lastname email 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 的记录:

Example (MySQLi 面向对象)

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// 创建数据库连接
$conn = new mysqli($servername, $username, $password, $dbname);
// 检查数据库连接
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// 删除记录sql
$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();
?>

Example (MySQLi 面向过程)

<?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
$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);
?>

Example (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 "Record deleted successfully";
    }
catch(PDOException $e)
    {
    echo $sql . "<br>" . $e->getMessage();
    }

$conn = null;
?>

当记录被删除之后,表中的数据如下:

id firstname lastname email 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