Why won't the following PDO transaction won't work in PHP?

Posted by jfizz on Stack Overflow See other posts from Stack Overflow or by jfizz
Published on 2013-06-29T22:18:36Z Indexed on 2013/06/29 22:21 UTC
Read the original article Hit count: 175

Filed under:
|
|
|
|

I am using PHP version 5.4.4, and a MySQL database using InnoDB. I had been using PDO for awhile without utilizing transactions, and everything was working flawlessly. Then, I decided to try to implement transactions, and I keep getting Internal Server Error 500. The following code worked for me (doesn't contain transactions).

try {
     $DB = new PDO('mysql:host=localhost;dbname=database', 'root', 'root');
     $DB->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

     $dbh = $DB->prepare("SELECT * FROM user WHERE username = :test");

     $dbh->bindValue(':test', $test, PDO::PARAM_STR);

     $dbh->execute();
    }
catch(Exception $e){
        $dbh->rollback();
        echo "an error has occured";
    }

Then I attempted to utilize transactions with the following code (which doesn't work).

try {
    $DB = new PDO('mysql:host=localhost;dbname=database', 'root', 'root');
    $DB->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $dbh = $DB->beginTransaction();

    $dbh->prepare("SELECT * FROM user WHERE username = :test");

    $dbh->bindValue(':test', $test, PDO::PARAM_STR);

    $dbh->execute();

    $dbh->commit();
    }
catch(Exception $e){
        $dbh->rollback();
        echo "an error has occured";
    }

When I run the previous code, I get an Internal Server Error 500.

Any help would be greatly appreciated! Thanks!

© Stack Overflow or respective owner

Related posts about php

Related posts about mysql