try {
$DSN = "mysql:host=localhost;dbname=dadao;port:3366";
$pdo = new PDO ($DSN, "root", "");
$pdo->setattribute (Pdo::attr_errmode, pdo::errmode_exception);
$pdo->begintransaction ();
$sql = "INSERT into user (username) VALUES (: username)";
$stmt = $pdo->prepare ($sql);
$stmt->execute (Array (': username ' = ' + ' Insert Title1 '));
$stmt->execute (Array (': Username ' =>null));
$pdo->commit ();
} catch (Exception $e) {
Echo ' transaction exception, now rolling back ';
echo $e->getmessage ();
Rolling back a transaction
$pdo->rollback ();
}
A simple transaction code, the database table in user username is not allowed to be empty. Tip: The transaction exception is now rolled back to Column ' username ' cannot be null1, and the database table is not written. However, the $pdo->setattribute (Pdo::attr_errmode, pdo::errmode_exception) is removed, there is no prompt, and there is a record insert in the database. $pdo->setattribute (Pdo::attr_errmode, pdo::errmode_exception); This line of code is not set is the wrong way to prompt, why it will affect the insertion of the database.
Reply to discussion (solution)
Yes, set the error handling method
No $pdo->setattribute (Pdo::attr_errmode, pdo::errmode_exception);
Try ... catch structure does not take effect
$pdo->rollback (); can never be executed