Skip to main content
6 of 7
edited tags
Reinderien
  • 71.1k
  • 5
  • 76
  • 256

Using a transaction to create account records

This is my first time using commit and rollback. I just need to know if this is a proper execution of the functions for this particular situation:

<?php
  include("../include/sessions.php");

  if(isset($_POST['addcriteria'])) {
    $value = $_POST['addcriteria'];

    $addname = isset($value['addname ']) ? $value['addname '] : '';
    $addemail = isset($value['addemail']) ? $value['addemail'] : '';
    $addcomment = isset($value['addcomment']) ? $value['addcomment'] : '';

    try {
      $dbc->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

      $dbc->beginTransaction();

      $selectCheck = $dbc->prepare("SELECT * FROM mainTable WHERE `name` = :newname AND `email` = :newemail");

      $selectCheck->bindParam(':newname', $addname);
      $selectCheck->bindParam(':newemail', $addemail);

      if($selectCheck->execute()) {
        $count = $selectCheck->rowCount();

        if($count > 0) {
          echo "Error: Account already exists";
        } else {
          $select = $dbc->prepare("SELECT MAX(uid)+1 AS 'NEWUID' FROM mainTable");

          if($select->execute()) {
            $row = $select->fetch(PDO::FETCH_ASSOC);
            $addnewuid = $row['NEWUID'];

            $insert = $dbc->prepare("INSERT INTO mainTable (`name`,`email`) VALUES (:addname,:addemail)");

            $insert->bindParam(':addname', $addname);
            $insert->bindParam(':addemail', $addemail);

            $insert->execute();

            $insertComment = $dbc->prepare("INSERT INTO comments (`name`,`comments`) VALUES (:name, :comment)");

            $insertComment->bindParam(':name', $addname);
            $insertComment->bindParam(':comment', $addcomment);

            $insertComment->execute();
          }
        }
      } else {
        echo "error: There was an unexpected error.";
      }

      $dbc->commit();

      $dbc = null;
      
    } catch(PDOException $e) {
        echo "error: " . $e->getMessage();
        $dbc->rollBack();
    }
  }
?>

Does this appear as proper use of the commit and rollback functions?

What, if anything, can I do to improve this code?

Am I missing anything?