首页 > 解决方案 > How to check if both query excecuted successfully?

问题描述

I want to INSTERT into 2 different tables. People will complete a form, where they enter their user data, and their company data. I tested this form, and when everything correct it's fine but...when the user data is ok, and the company data has errors, the user insert runs and I don't want it. Vica versa.. My code right now: (just a markup)

$sql = "INSERT INTO user (name, email, password) VALUES (:username, :email, :password)";
  $stmt = $dbh->prepare($sql) {
    ... //bind parameters
    if($stmt->execute()){
      echo "Successfully registered user";
    $sql = "INSERT INTO company (title, number, address) VALUES (:title, :number, :address)";
      $stmt = $dbh->prepare($sql) {
        ... //bind parameters
        if($stmt->execute()){
        echo "Successfully registered company";
      }
    }
  }
}
unset($stmt);

I want to check both, and when there is no error, then run both query. How do I nest it?

标签: phpmysqlnestedlogic

解决方案


您可以将 transactions beginTransaction, rollBack,commit与 try 和 catch 一起使用。

$dbh->beginTransaction()
try {
$sql = "INSERT INTO user (name, email, password) VALUES (:username, :email, :password)";
  $stmt = $dbh->prepare($sql) {
    ... //bind parameters
    if($stmt->execute()){
      echo "Successfully registered user";
    $sql = "INSERT INTO company (title, number, address) VALUES (:title, :number, :address)";
      $stmt = $dbh->prepare($sql) {
        ... //bind parameters
        if($stmt->execute()){
        echo "Successfully registered company";
      }
    }
  }
}
} catch(\Exception $e) 
    $dbh->rollBack();
}
$dbh->commit();
unset($stmt);


推荐阅读