0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

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

Last updated at Posted at 2020-11-21

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();
}

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?