【问题标题】:Using PDO and transactions, but I dont get error so rollback wont work.使用 PDO 和事务,但我没有收到错误,所以回滚不起作用。
【发布时间】:2014-03-17 09:54:56
【问题描述】:

我正在尝试在 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();

【问题讨论】:

    标签: php mysql pdo transactions rollback


    【解决方案1】:

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

    查看here了解更多详情。

    【讨论】:

      猜你喜欢
      • 2015-07-14
      • 1970-01-01
      • 2012-12-10
      • 2022-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-25
      • 2011-01-17
      相关资源
      最近更新 更多