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