mardi 5 mai 2015

Best way to relate the order ID with the products that belongs to it


I'm developing a shop system and I'm using the only method I was able to find to relate the ID of the order with the products that belongs to it.
When someone purchase something, first the order is added to the table orders with their details, including the ID of that order (order_id), that is auto incremented by the SQL.
I use this to add an order to the table orders:

INSERT INTO orders SET customer_id = '{$customer_id}', customer_name = '{$user['customer_name']}', order_price = '{$total_price}', order_date = '{$date}'"

Ok, the order was added. Now, in sequence, the products that belongs to that order will be added to another table, the table purchased_products.
I use PDO lastInsertId() to get the last inserted order_id from the table orders and then add each product of that order with a Foreign Key order_id in another table called purchased_products. To do this, I use:

$respective_order_id = $connection->lastInsertId();

foreach($_SESSION['cart'] as $product)
{
    sql = "INSERT INTO purchased_products SET order_id = '{$respective_order_id}', product_name = '{$product['product_name']}', product_price = '{$product['product_price']}', quantity = '{$product['quantity']}'";
}

These codes run simultaneously. First the order will be added in the orders table with their order_id auto incremented, and then all the products of that order will also be added to the purchased_products table and the Foreign Key order_id of each one of them will have the value of the last order_id inserted in the orders table. Later I will can display any order with their products by consulting it with the Foreign Key order_id.
So far, it's working well. And as I said, this was the only way I found to assign the ID of the order with the products that belongs to it. My question is: is this secure? How about if several people buy the same time? There is the risk of the IDs be exchanged or the products not added/or goes to the wrong order? I would be immensely grateful if someone experienced answer these questions because this is making me afraid, I'm wondering if I can trust in this method.

Aucun commentaire:

Enregistrer un commentaire