-2

Below code i just not add third parameter in fQuery statement , second query is correct. but as i understand that transaction provide Atomicity if first query is failed than second should not be executed but in my code first query give error & second query executed successfully.

$db = new PDO("mysql:host=127.0.0.1;dbname=stock",'root','') ;

$name = 'name' ;
$mobile = 1234567890 ;
$email = 'email@gmail.com'  ;

try {

    $db->beginTransaction();

    $fQuery = "INSERT INTO investor (name,mobile,email) values (:n,:m,:e) " ;
    $fstmt = $db->prepare($fQuery) ;
    $fstmt->execute([':n'=>$name,':m'=>$mobile]);

    $sQuery = "INSERT INTO testing (name) values (:e) " ;
    $sstmt = $db->prepare($sQuery) ;
    $sstmt->execute([':e'=>$email]);

    $db->commit();

} catch (Exception $e) {
    $db->rollBack();
    echo "Failed: " . $e->getMessage();
}
delboy1978uk
  • 12,118
  • 2
  • 21
  • 39
leecarter
  • 1,095
  • 1
  • 11
  • 14
  • apply this http://php.net/manual/en/pdo.error-handling.php to your code; what does it show? – Funk Forty Niner Sep 05 '18 at 11:46
  • 2
    you're trying to deliberately cause an error; that isn't how you check if a query/transaction failed or not. The query itself must be valid; the first one will fail as a syntax error. – Funk Forty Niner Sep 05 '18 at 11:48
  • Might be because passing fewer parameters to `PDOStatement::execute()` triggers a PHP Warning (SQLSTATE[HY093]: Invalid parameter number) - it's not an exception and therefore cannot be caught. – Darragh Enright Sep 05 '18 at 11:52
  • @Darragh yes `email` is nullable column – leecarter Sep 05 '18 at 11:54

1 Answers1

2

PDO won't throw exceptions unless you tell it to.

$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
delboy1978uk
  • 12,118
  • 2
  • 21
  • 39