gpt4 book ai didi

php - SQL 查询插入检查事务内并回滚

转载 作者:行者123 更新时间:2023-11-29 21:59:19 25 4
gpt4 key购买 nike

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

$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 因为它会自行检查错误?

最佳答案

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

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

关于php - SQL 查询插入检查事务内并回滚,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32814036/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com