0
votes

Here is my script:

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;

}

As you see there is an throw before commit(). Is that fine? Actually when I run it, it won't work and throws this error:

Fatal error: Uncaught exception 'Exception' in C:\xampp\htdocs\myweb\others\login.php:341 Stack trace: #0 C:\xampp\htdocs\myweb\application\other.php(35): login->resend_password_check() #1 C:\xampp\htdocs\myweb\index.php(150): require_once('C:\xampp\htdocs...') #2 {main} thrown in C:\xampp\htdocs\myweb\others\login.php on line if ( !$stm->rowCount() ) { throw new Exception('something is wrong'); }

How can I fix it?

1
Are you using namespaces? Seems your code isn't finding your Exception class. BTW: It's ok to throw exceptions before the commit. PS.: I know that this is not the context but, having exit in your code is not good. Let the request flow finish gracefullyWilliam Okano

1 Answers

0
votes

php Fatal error is not catchable.

When you use pdo don't write throw new Exception('something is wrong'); because PDO already have this expression 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;
}