当我运行这段代码时
<?php
include '../bin/config.php';
connect();
if (isset($_GET['id']) && is_numeric($_GET['id'])){
$id = $_GET['id'];
$stmt = $conn->prepare("DELETE FROM noteline WHERE Nid = ?");
$stmt->bindParam(1, $id, PDO::PARAM_INT);
$outcome = $stmt->execute();
if ($outcome){
echo 'it was successfully deleted';
header("Location: ../noteline");
}else {
echo 'it was not successful due to something';
}
}
?>
它回显“已成功删除”,但我的数据库中没有删除任何内容... 但是当我通过修改此代码开始交易时,如下所示:
<?php
include '../bin/config.php';
connect();
if (isset($_GET['id']) && is_numeric($_GET['id'])){
$id = $_GET['id'];
$stmt = $conn->prepare("DELETE FROM noteline WHERE Nid = ?");
$stmt->bindParam(1, $id, PDO::PARAM_INT);
$conn->beginTransaction();
$outcome = $stmt->execute();
if ($outcome){
$conn->commit();
echo 'it was successfully deleted';
header("Location: ../noteline");
}else {
echo 'it was not successful due to something';
}
}
?>
我的数据终于从我的 MySQL 数据库中删除了! 我想知道为什么?
最佳答案
因为 PDO 连接在禁用自动提交模式的情况下运行。查看 connect()
函数以确保您没有禁用此模式。
(此外,我发现您正在使用全局变量来存储连接对象。尽可能避免全局变量。)
关于php - 为什么我必须使用 PDO 启动事务,然后提交它才能从 MySQL DB 中删除数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13301826/