使用回滚在事务内部进行SQL查询插入检查

时间:2015-09-27 23:51:57

标签: php mysql pdo

在我的商店系统中,我使用此代码插入数据库客户订单详细信息以及属于该客户订单的产品:

$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>";
}

我的问题是关于错误检查的代码优化。 我建议使用if ($query),即使我正在使用catchrollBack?这是必要的,或者我只能使用catchrollBack,因为它会自行检查错误吗?

1 个答案:

答案 0 :(得分:0)

如果您将PDO错误设置为抛出异常,则无需使用if

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