سؤال

I am trying to create a simple class in 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;
}
}

But when I do the following I get no errors, no matter what i do to the querys, resulting in the rollback function being completly useless. The querys are still submitted, even though the querys might be totally messed up..!

<?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();
هل كانت مفيدة؟

المحلول

Make sure PDO error mode is set to: PDO::ERRMODE_EXCEPTION. Otherwise, you'll need to check the error state after every query.

Check here for further details.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top