gpt4 book ai didi

php - 使用 PDO 和事务,但我没有收到错误,因此回滚不起作用。

转载 作者:行者123 更新时间:2023-11-29 13:12:59 24 4
gpt4 key购买 nike

我正在尝试在 php 中创建一个简单的类,

<?php
class DB{

private $db_host = "localhost";
private $db_usr = "root";
private $db_pass = "";
private $db_name = "webbshop";
private $db;

function __construct(){
$this->db = new PDO('mysql:host=' . $this->db_host . ';'
.'dbname=' . $this->db_name, $this->db_usr, $this->db_pass);
}

function Trans(){
$this->db->beginTransaction();
}

function query($sql){
$stmt = $this->db->prepare($sql);
$stmt->execute();
return $stmt->fetchAll();
}

function lastInsertID() {
return $this->db->lastInsertId();
}

function commitTrans(){
$this->db->commit();
}

function rollback() {
$this->db->rollBack();
}

function __destruct() {
$this->db = null;
}
}

但是,当我执行以下操作时,无论我对查询执行什么操作,都不会出现错误,导致回滚功能完全无用。即使查询可能完全困惑,查询仍然会提交......!

<?php
require 'db_con.php';

$db = new DB();
$db->Trans();
$nick = "INSERT INTO `webbshop`.`user` (`userID`, `nick`, `pass`) VALUES (NULL, '$_POST[nick]', '$_POST[pass]')";

try {
$db->query($nick);
$nickID = $db->lastInsertID();
echo $nickID;

$pers = "INSERT INTO `webshop`.`person` (`personID`, `userID`, `fname`, `lname`, `persnr`, `email`) VALUES (NULL, $nickID, '$_POST[firstname]', '$_POST[lastname]', '$_POST[personnr]','$_POST[email]')";
$addr = "INSERT INTO `webshop`.`address` (`addressID`, `userID`, `street`, `city`, `zip`) VALUES (NULL, $nickID, '$_POST[address]', '$_POST[city]', '$_POST[zip]')";

$db->query("INSERT INTO `wshop`.`persn` (`personID`, `userID`, `fname`, `lname`, `persnr`, `email`) VALUES (NULL, $nickID, '$_POST[firstname]', '$_POST[lastname]', '$_POST[personnr]','$_POST[email]')");
$db->query($addr);

} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "</br>";
$db->rollback();
}
$db->commitTrans();

最佳答案

确保 PDO 错误模式设置为:PDO::ERRMODE_EXCEPTION。否则,您需要在每次查询后检查错误状态。

检查here了解更多详情。

关于php - 使用 PDO 和事务,但我没有收到错误,因此回滚不起作用。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21840331/

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