2015-09-27 60 views
0

在我的商店系统我使用这个代码在DB客户订单的详细信息插入和属于该○产品:内有ROLLBACK TRANSACTION SQL查询插入检查

$connection->beginTransaction(); 
try 
{ 
    $sql = "INSERT INTO orders (customer_id, order_price, order_date, order_hour) 
      VALUES (?, ?, ?, ?)"; 

    $query = $connection->prepare($sql); 
    $query->execute(array 
    (
     $user['user_id'], 
     $order_price, 
     $date, 
     $hour 
    )); 

    if($query) 
    { 
     $id_of_respective_order = $connection->lastInsertId(); 

     $sql = "INSERT INTO purchased_products (order_id, product_name, product_price, quantity, extras) 
       VALUES (?, ?, ?, ?, ?)"; 

     $query = $connection->prepare($sql); 

     foreach($_SESSION['cart'] as $product) 
     { 
      $extras = null; 
      $product_price = $product['product_price'] * $product['quantity']; 

      if($product['extras'] != NULL) 
      { 
       foreach($product['extras'] as $extra) 
       { 
        $extras .= $extra['extra_quantity'] ."x". $extra['extra_name'] ."<br/>"; 
        $product_price += $extra['extra_total'] * $product['quantity']; 
       } 
      } 

      $query->execute(array 
      (
       $id_of_respective_order, 
       $product['product_name'], 
       $product_price, 
       $product['quantity'], 
       $extras 
      )); 
     } 

     unset($_SESSION['cart']); 

     echo "<script>alert('Your purchase was completed!'); 
     window.location = '/my-orders.php'; 
     </script>"; 
    } 
    else 
    { 
     echo "<script>alert('An error ocurred while completing your purchase. Please try again!'); 
     window.location = '/my-cart.php';</script>"; 
    } 
    $connection->commit(); 
} 
catch(PDOException $exception) 
{ 
    $connection->rollBack(); 
    echo "<script>alert('An error ocurred while completing your purchase. Please try again!'); 
    window.location = '/my-cart.php';</script>"; 
} 

我的问题是关于中为代码优化进行错误检查。 即使在catchrollBack上我推荐使用if ($query),因为我正在做这件事吗?这是必要的或我可以只使用catchrollBack,因为它会自行检查错误?

回答

0

如果您的PDO错误设置为抛出异常,则不需要使用if

$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);