runoops.com

PHP MySQL Delete

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


删除数据库中的数据

DELETE FROM 语句用于从数据库表中删除记录。

语法

DELETE FROM table_name
WHERE some_column = some_value

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

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

下面的实例将从 "myguests" 表中选取所有 email='john@example.com' 的行并删除:


使用 MySQLi

MySQLi - 面向对象:

实例

<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "mydb";
 
// 创建连接
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("连接失败: " . $conn->connect_error);
} 
 
 $sql = "DELETE FROM myguests WHERE email = ?";

//创建预处理语句
$stmt  = $conn->prepare($sql);
$email = 'john@example.com';
//绑定参数
$stmt->bind_param("s",$email);

//执行SQL
$stmt->execute();

$conn->close();
?>

MySQLi - 面向过程:

实例

<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "mydb";
 
// 创建连接
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
    die("连接失败: " . mysqli_connect_error());
}
 
$sql = "DELETE FROM myguests WHERE email = ?";
$email = 'john@example.com';

$stmt = mysqli_prepare($conn, $sql);

//绑定参数
mysqli_stmt_bind_param($stmt, "s",$email);

//执行SQL
mysqli_stmt_execute($stmt);

mysqli_close($conn);
?>

使用 PDO (+ 预处理)

以下实例使用了预处理语句删除数据。

实例

<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "mydbpdo";
 
try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $sql = "DELETE FROM myguests WHERE email = :email";
    $stmt = $conn->prepare($sql); 

    // 执行预处理语句
    $stmt->execute([':email' => 'john@example.com']);

    //或者这样
    //$stmt->bindValue(":email", 'john@example.com');
    // 执行预处理语句
    //$stmt->execute();
}
catch(PDOException $e) {
    echo "Error: " . $e->getMessage();
}
$conn = null;
?>

Captcha Code

0 笔记

分享笔记

Inline Feedbacks
View all notes