21xrx.com
2024-12-24 10:17:07 Tuesday
登录
文章检索 我的文章 写文章
PHP MySQL删除数据
2021-07-25 07:08:49 深夜i     --     --
PHP MySQL删除数据


使用mysqli和pdo从MySQL表中删除数据

DELETE语句用于从表中删除记录:

DELETE FROM table_name
WHERE some_column = some_value

请注意删除语法中的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的记录:

<?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 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

 

 

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复
    相似文章