gpt4 book ai didi

php - 为什么这个 PDO 回滚不起作用?

转载 作者:可可西里 更新时间:2023-11-01 07:46:07 24 4
gpt4 key购买 nike

<分区>

我在 PHP 和 MySQL 数据库中使用 PDO。我想要做的是每当插入失败时(例如唯一字段中的重复条目),让它抛出异常错误消息并回滚更改(在我的情况下不是自动递增)。

这就是我所做的,但它不起作用:

try {
$email = $_POST['Email'];
$FirstName = $_POST['FirstName'];
$LastName = $_POST['LastName'];

$query="INSERT INTO subscriber (Email,FirstName,LastName,CreateDate) VALUES (?,?,?,CURDATE())";
$stmt = $conn->prepare($query);

$stmt->bindParam(1, $email , PDO::PARAM_STR);
$stmt->bindParam(2, $FirstName, PDO::PARAM_STR);
$stmt->bindParam(3, $LastName, PDO::PARAM_STR);

$stmt->execute();
}
catch(PDOException $e) {
die ($e->getMessage().'<a href="addSub.php"> Back</a>');
$conn->rollBack();
}

我哪里出错了?

这是它的编辑版本(插入的整个部分),对吗?谢谢

if($_SERVER['REQUEST_METHOD'] == "POST"){


$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->beingTransaction();
try {

$email = $_POST['Email'];
$FirstName = $_POST['FirstName'];
$LastName = $_POST['LastName'];


$query="INSERT INTO subscriber (Email,FirstName,LastName,CreateDate) VALUES (?,?,?,CURDATE())";
$stmt = $conn->prepare($query);


$stmt->bindParam(1, $email , PDO::PARAM_STR);
$stmt->bindParam(2, $FirstName, PDO::PARAM_STR);
$stmt->bindParam(3, $LastName, PDO::PARAM_STR);

$conn->commit();

}
catch(PDOException $e)
{
die ($e->getMessage().'<a href="addSub.php"> Back</a>');
$conn->rollBack();
}


try {
$userID = $_SESSION['username'];
$query="INSERT INTO list_sub (SubID,ListID) VALUES ('',$_SESSION[ListID])";
$stmt = $conn->prepare($query);

$conn->commit();

}
catch(PDOException $e)
{
$conn->rollBack();
die ($e->getMessage().'<a href="addSub.php"> Back</a>');
}

$conn = null;
}

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com