سؤال

I must miss something but I have a very strange behaviour with PDO (MySQL).

$req = null;
try {
    $sql = 'INSERT INTO inexistant_table (idmember) VALUES(:idmember)';
    $req = $db->prepare($sql);
    $req->bindParam(':idmembre', $_SESSION['ID']);
    $req->execute();
}
catch (PDOException $e) {
    echo 'exception';
}

if( !$req ) {
    echo 'false';
}
echo 'success';

Then I don't get any error, it only prints 'success'. Any idea?

EDIT: $db->errorCode() returns 00000.

هل كانت مفيدة؟

المحلول

The outcome is explained as such,

Exceptions are not enabled - no "exception"

To enable exceptions, as per Fred -ii-'s comment, thanks! ;-)

$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

(Also see Reference - frequently asked questions about PDO)

The wrong value is being checked - no "false"

The $req variable represents the prepared statement object, not the result of such executing such a statement. Compare with the following that checks the result.

$result = $req->execute();
// ..
if (!$result) { /* fail! */ }
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top