-1

EDIT I dont believe this is a duplucatie question of that mysqli question, and do believe it deserves to be a question on its own.

So I'm trying to get some data from a form into the correct tables, using PDO Transactions (this is new to me).

The SQL inserts correctly into the tables, but double. So I end up with a double result in each table.

I read about there being an issue with the page refreshing twice because of the favicon, or this being a browser issue. But even after a restart of the server and multiple browsers tested, I think it's just my code.

try {
    //$mysqli->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $mysqli->begin_transaction();

    $stmt = $mysqli->prepare("INSERT $table1 (status, customer, product, ord_num, return_code, dop, sn, problem_descr, repair_descr, comments) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
    $stmt->bind_param("ssssssssss", $status, $customer, $product, $ord_num, $return_code, $dop, $sn, $problem_descr, $repair_descr, $comments);
    $stmt->execute();
    if (!$stmt->execute()) {
        echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
    }
    $stmt->close();

    $stmt = $mysqli->prepare("INSERT $table2 (part1, part2, part3, part4, part5, part6, part7, part8, part9, part10, part11, part12, part13, part14, part15, part16, part17, part18, part19, part20) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
    $stmt->bind_param("ssssssssssssssssssss", $part1, $part2, $part3, $part4, $part5, $part6, $part7, $part8, $part9, $part10, $part11, $part12, $part13, $part14, $part15, $part16, $part17, $part18, $part19, $part20);
    $stmt->execute();
    if (!$stmt->execute()) {
        echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
    }
    $stmt->close();

    $mysqli->commit();
} catch(PDOException $ex) {
    //Something went wrong, rolback!
    $mysqli->rollBack();
    echo $ex-getMessage();
}
Robin GM
  • 185
  • 1
  • 8

2 Answers2

2

This needs to change:

$stmt->execute();
        if (!$stmt->execute()) {

just

if (!$stmt->execute()) {

is enough.

Once you run $stmt->execute(); ones and then again put it inside the if statement to see if it returns true, you endup executing the statement twice. For which you are seeing the double entries.

Kamrul Khan
  • 3,260
  • 4
  • 32
  • 59
0

or you can do like this

$run = $stmt->execute();
if (!$run) {

We Just need to run the execute statement once.

Abdulla Nilam
  • 36,589
  • 17
  • 64
  • 85