那麼,我有兩種方法來存儲我的客戶購買的產品。但我想知道我應該使用哪一個,所以我在這裏得到一些意見。
第一種方法是:最好的方法來存儲客戶產品
try
{
$connection = new PDO("mysql:host={$HOST};dbname={$DB_NAME}", $USERNAME, $PASS);
}
$connection->beginTransaction();
$sql = "INSERT INTO orders (customer_id, customer_name, order_value, order_date)
VALUES (?, ?, ?, ?)";
$query = $connection->prepare($sql);
$query->execute(array
(
$user_id,
$user['user_name'],
$order_value,
$date
));
$id_of_respective_order = $connection->lastInsertId();
$sql = "INSERT INTO purchased_products (order_id, product_name, product_price, quantity)
VALUES (?, ?, ?, ?)";
$query = $connection->prepare($sql);
foreach($_SESSION['cart'] as $product)
{
$query->execute(array
(
$id_of_respective_order,
$product['product_name'],
$product['product_price'],
$product['quantity']
));
}
$connection->commit();
現在讓我們來解釋一下:上面我插入一個表格和所購買的產品在另一個表中的順序,和之後的方法我可以顯示所購買產品的每一個通過使用purchased_products
表中的Foreign Key
order_id
表格中的任何客戶。
現在我有第二個方法:
try
{
$connection = new PDO("mysql:host={$HOST};dbname={$DB_NAME}", $USERNAME, $PASS);
}
$connection->beginTransaction();
$sql = "INSERT INTO orders (customer_id, customer_name, order_value, order_date, purchased_products)
VALUES (?, ?, ?, ?, ?)";
$purchased_products = null;
foreach($_SESSION['cart'] as $product)
{
$purchased_products .= "
<table>
<tr>
<th>Product Name</th>
<th>Product Price</th>
<th>Quantity purchased</th>
</tr>
<tr>
<td>{$product['product_name']}</td>
<td>{$product['product_price']}</td>
<td>{$product['quantity']}</td>
</tr>
</table>
";
}
$query = $connection->prepare($sql);
$query->execute(array
(
$user_id,
$user['user_name'],
$order_value,
$date,
$purchased_products
));
$connection->commit();
使用這種方法,我可以展示產品直接在表中只能用表鍵purchased_products
。 什麼方法最好?如果我使用第一個,我可以用這個值進行操作,但是......我一直在研究並瞭解到插入是製造瓶頸。購買ID是自動分配的,然後我使用lastInsertionId來確定哪些產品屬於上次購買。但是這意味着如果兩個人同時購買會有錯誤?一個人將不得不等待手術完成,因爲瓶頸或者我不會有問題?我可以信任單獨的插入,還是應該將所有內容插入一張表中作爲第二種方法?
第二種方法還創建了每個條目259個字符*的開銷,該字段約佔整個字段的90%,假設產品名稱爲「我的示例產品」,價格爲「123.45£」,數量爲「42」。在整個行中,這可能會減少到浪費空間的70%,但這仍然是巨大的。 – Siguza
我實際上使用第一種方法,並使用外鍵order_id進行查詢,正如我在問題中提到的:'SELECT * FROM orders o,purchased_products pp WHERE o.customer_id LIKE {$ user_id} AND pp.order_id = o.order_id ORDER BY o.order_id DESC'工作正常。在你的回答中,我只是沒有想到你對這種方法意味着什麼。你能更具體嗎? – Dyan
@Siguza。 。 。規範化的數據通常需要額外的空間。外鍵引用可以改善這個問題。你應該學習適當的'join'語法。第一種方法更適合回答關於數據庫中產品和訂單的問題。 –