我正在使用这个类来处理pdo连接和数据库操作,但是我无法让rollback函数工作。我在$pers查询中创建了一个故意错误,得到以下错误:

( ! ) Warning: PDO::query(): SQLSTATE[42S02]: Base table or view not found: 1146 Table 'webbshop.prson' doesn't exist in C:\wamp\www\webbshop\includes\db_con.php on line 21

但其他两个查询仍在执行,添加到数据库中,并且不会回滚。我该怎么做才能让一切正常运转?
我在另一篇文章中读到你需要使用InnoDB,所以我运行了SHOW ENGINES sql命令,它说对InnoDB的支持是默认的,评论说:“支持事务、行级锁定和外键”
PDO连接类:
<?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);
    $this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
}

function error(){

}   €$€$£

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

function insert($sql){
    $stmt = $this->db->query($sql);
}

function fetch($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';

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

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

    $db->insert($pers);
    $db->insert($addr);

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

最佳答案

你在用InnoDB吗?要使用事务,应该使用InnoDB,否则回滚将不起作用!
编辑:
尝试将PDO::ERRMODE_警告更改为PDO::ERRMODE_异常

关于php - PHP PDO错误消息返回,但回滚不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21881925/

10-09 20:23
查看更多