1つ関数内で複数のSQL文を実行する場合の処理なのですが、下記ソースのように2回(実行回数)「execute();」を使用して処理してしまっても、可読性など問題はないでしょうか。
こうすれば可読性が上がったり、短縮してかけるよ、という事があればご教授いただけると、大変助かります。
lang
1function cuteInsert() { 2 $dbh = connectDb(); 3 $dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); 4 5 // 1回目 6 $post_id = h($_POST['post_id']); 7 $sql = "insert into post_ip(post_id, remote_addr, user_agent, created ) values (:post_id, :remote_addr, :user_agent, now())"; 8 $stmt = $dbh->prepare($sql); 9 $stmt->setFetchMode(PDO::FETCH_ASSOC); 10 $stmt->bindValue(':remote_addr', $_SERVER['REMOTE_ADDR'], PDO::PARAM_STR); 11 $stmt->bindValue(':user_agent', $_SERVER['HTTP_USER_AGENT'], PDO::PARAM_STR); 12 13 try { 14 $stmt->execute(); 15 } catch (\PDOException $e) { 16 throw new \Exception('今日は投稿できません。'); 17 } 18 19 // 2回目 20 $eva = h($_POST['evaluation']); 21 if ($eva == "0") { 22 $evaluation = 1; 23 } else { 24 $evaluation = $eva + 1; 25 } 26 27 $cute_sql = "update post set evaluation = :evaluation where post_id = :post_id"; 28 29 $stmt = $dbh->prepare($cute_sql); 30 $stmt->setFetchMode(PDO::FETCH_ASSOC); 31 $stmt->bindParam(':post_id', $post_id, PDO::PARAM_INT); 32 $stmt->bindParam(':evaluation', $evaluation, PDO::PARAM_INT); 33 $stmt->execute(); 34 35 return $evaluation; 36 }
↓Kosuke_Shibuyaさん、KiyoshiMotokiさんにご指摘いただいた内容を加味し、ソースを修正しました。
lang
1 function cuteInsert() { 2 $dbh = connectDb(); 3 // $post_id = h($_POST['post_id']); から変更 4 $post_id = filter_input(INPUT_POST, 'post_id'); 5 6 $sql = "insert ignore into post_ip(post_id, remote_addr, user_agent, created ) values (:post_id, :remote_addr, :user_agent, now())"; 7 $dbh->beginTransaction(); 8 $stmt = $dbh->prepare($sql); 9 $stmt->bindValue(':post_id', $post_id, PDO::PARAM_INT); 10 $stmt->bindValue(':remote_addr', $_SERVER['REMOTE_ADDR'], PDO::PARAM_STR); 11 $stmt->bindValue(':user_agent', $_SERVER['HTTP_USER_AGENT'], PDO::PARAM_STR); 12 $stmt->execute(); 13 $count = $stmt->rowCount(); 14 15 // 登録できた場合 16 if ($count == "1") { 17 $eva = filter_input(INPUT_POST, 'evaluation'); 18 if ($eva == "0") { 19 $evaluation = 1; 20 } else { 21 $evaluation = $eva + 1; 22 } 23 24 $cute_sql = "update post set evaluation = :evaluation where post_id = :post_id"; 25 26 $stmt = $dbh->prepare($cute_sql); 27 $stmt->bindValue(':post_id', $post_id, PDO::PARAM_INT); 28 $stmt->bindValue(':evaluation', $evaluation, PDO::PARAM_INT); 29 $stmt->execute(); 30 $dbh->commit(); 31 // 登録できなかった場合 32 } else { 33 $dbh->rollBack(); 34 } 35 }
回答2件
あなたの回答
tips
プレビュー
下記のような回答は推奨されていません。
このような回答には修正を依頼しましょう。
2015/11/24 08:25
2015/11/25 03:24
退会済みユーザー
2015/11/27 19:35
退会済みユーザー
2015/11/27 19:38
2015/11/30 03:10