有交易

时间:2016-07-13 21:07:02

标签: php mysql pdo transactions throws

这是我的剧本:

try{

    $dbh_conn->beginTransaction();

    $user_id = $_POST['iuser_id'];
    $token   = hash('sha512', bin2hex(openssl_random_pseudo_bytes(16)).$user_id);

    $stmt = $dbh_conn->prepare("UPDATE resend_pass SET active = 0 WHERE user_id = ?");
    $stmt->execute(array($user_id));

    $stm = $dbh_conn
    ->prepare("INSERT INTO resend_pass(user_id, token, date_time)
                SELECT ?, ?, unix_timestamp()
                FROM dual
                WHERE NOT EXISTS( SELECT count(*) AS num_week,
                                    FROM resend_pass
                                   WHERE user_id   = ?  
                                     AND date_time > unix_timestamp() - 604800
                                  HAVING num_week > 11 ;");
    $stm->execute(array($user_id, $token, $user_id));

    // no row inserted (either there is lots of reuqests or duplicate token)
    if ( !$stm->rowCount() ) { throw new Exception('something is wrong'); }

    $dbh_conn->commit();

    /* sending an email contains reset_password_token here */

    $_SESSION["TopMSG"] = "<div class='msg_success'>has been sent</div>";
    header('location: ../login');
    exit;

} catch(Exception $e) {

    $dbh_conn->rollBack();

    $_SESSION["TopMSG"] = "<div class='msg_success'>$e</div>";
    header('location: ../login');
    exit;

}

如您所见,throw之前有一个commit()。那很好吗?实际上,当我运行它时,它不会工作并抛出此错误:

  

致命错误:未捕获的异常&#39;异常&#39;在C:\ xampp \ htdocs \ myweb \ others \ login.php:341堆栈跟踪:#0 C:\ xampp \ htdocs \ myweb \ application \ other.php(35):login-&gt; resend_password_check()#1C :\ xampp \ htdocs \ myweb \ index.php(150):require_once(&#39; C:\ xampp \ htdocs ...&#39;)#2 {main}在C:\ xampp \ htdocs \ myweb中抛出第if ( !$stm->rowCount() ) { throw new Exception('something is wrong'); }行上的\ others \ login.php

我该如何解决?

1 个答案:

答案 0 :(得分:0)

php致命错误无法捕获。

当你使用pdo时,不要写新的例外(&#39;有些事情是错的&#39;); 因为PDO已经有了这个表达式PDOException

for axample:

try{
    $dbh_conn->beginTransaction();
    .......
    .......
    $stm->execute(array($user_id, $token, $user_id));
    ......
    $dbh_conn->commit();

}catch(PDOException $e) {
    print_r($e->getMessage());//Show excption message
    $dbh_conn->rollBack();
    $_SESSION["TopMSG"] = "<div class='msg_success'>$e</div>";

    //header('location: ../login');
    exit;
}