PDO lastInsertId:它最终可能会失败?

时间:2015-09-15 14:51:50

标签: php mysql pdo

在我的商店系统中,我正在使用PDO lastInsertId通过这种方式将order_id分配给属于它的产品:

$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
    ));

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

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

我的问题是:这可能会失败并为产品分配错误的订单ID吗?我搜索并发现人们只是说我可以盲目地信任这种方法,这是100%安全的,甚至因为我的数据库是InnoDB并且有交易支持。我尽可能准确地让代码尽可能准确,但有些东西需要改进或改变?我希望得到一个使用这种方法的人的确切答案。我可以为我的客户启动这个系统吗?

0 个答案:

没有答案