Help us understand the problem. What is going on with this article?

【DB接続後sqlを渡すパターン】

beginTransaction()commit()の使い方をわかっていなかったのでメモ

一つのsql文ですむ場合
prepare()execute()だけでいい

try{
    $db = new PDO('mysql:host=localhost;dbname=users','root','pass');
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERROMODE_EXCEPTION);
}catch(PDOException $e){
    print $e->Message();
}
$sql = 'INSERT INTO users (name) VALUES (?)';
$stmt = $db->prepare($sql);
$stmt->execute("taro");

関連する複数のsqlをinsertなどしたい場合(どれかが欠けるとおかしくなる時)
beginTransaction()を使って、失敗したらrollbackさせる。

try{
    $db = new PDO('mysql:host=localhost;dbname=users','root','pass');
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERROMODE_EXCEPTION);
}catch(PDOException $e){
    print $e->Message();
}

try{
    $db->beginTransaction();
    $sql1 = 'INSERT INTO users (name) VALUES (?)';
    $stmt = $db->prepare($sql1);
    $stmt->execute("taro");

    $sql2 = 'INSERT INTO orders (order_name) VALUES (?)';
    $stmt = $db->prepare($sql2);
    $stmt->execute("rice");

    $sql3 = 'INSERT INTO prices (price) VALUES (?)';
    $stmt = $db->prepare($sql3);
    $stmt->execute(200);

    $dbh->commit();
}catch(Exception $e){
    $db->rollback();
    print $e->Message();
}

Ueken3pei
大学3年生の上野健助といいます😀 初学者です。アウトプットがんばります〜
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away