0

I was just trying out this code:

public function create_account($username, $password, $email) {
    $password = sha1($password);
    $activation_key = md5($username . $email);

    $this->STH = $this->DBH->prepare("INSERT INTO users(username, password, email, activation_key, created) VALUES(:username, :password, :email, :activation_key, :created)");
    $this->STH->bindParam(':username', $username);
    $this->STH->bindParam(':password', $password);
    $this->STH->bindParam(':email', $email);
    $this->STH->bindParam(':activation_key', $activation_key);
    $this->STH->bindParam(':created', time());
    $this->STH->execute();

    if ($this->DBH->lastInsertId()) {
        //$this->send_mail($username, $email);
        return true;
    } else {
        //Log
    }
}

Now it is working, indeed. But just a minute ago, I had missed a ) on the SQL statement, which led that the data was not inserted. I tried with the try { } catch block - But I didn't receive any error, still - Is it suppose to be so? How can I fix this code, to properly log the PDO error (if received)

John
  • 2,900
  • 8
  • 36
  • 65
  • 2
    Probably related: [How to squeeze error message out of PDO?](http://stackoverflow.com/q/3726505) – Pekka Nov 30 '11 at 15:48

2 Answers2

1

execute() returns a bool - just check for it. Basically you can use it like this :

if ($this -> STH -> execute() === false) {
    print_r($this -> STH -> errorInfo());
}
Tom van der Woerdt
  • 29,532
  • 7
  • 72
  • 105
  • 2
    Also, if you add a try/catch block and you have more than one insert, you might want to try using a transaction and rollback if an exception is thrown... – Homer6 Nov 30 '11 at 15:57
1

Have you tried catching the error using:

try {
    $this->STH->execute();
} catch (PDOException $pdostmtex) {
    echo('Exception encountered: '.$pdostmtex->getCode().' -> '.$pdostmtex->getMessage());
    exit;
}

And make sure your error reporting is on:

Taken from http://php.net/manual/en/function.error-reporting.php and used only as reference:

// Report all errors except E_NOTICE
// This is the default value set in php.ini
error_reporting(E_ALL ^ E_NOTICE);

// Report all PHP errors (see changelog)
error_reporting(E_ALL);
Nonym
  • 6,199
  • 1
  • 25
  • 21