我有包含类别名称的“输入标签”,这意味着我在每个产品中都有多个类别,因此我创建了一个“链接表”,该链接表将存储两个表的ID。
product table category table product_category table
+---+------------+ +---+------------+ +-----------+------------+
|id | name | |id | name | |product_id | category_id|
+---+------------+ +---+------------+ +-----------+------------+
| 1 | Cake | | 1 | Sweets | | 1 | 1 |
| 2 | Chocolate | | 2 | Dessert | | 1 | 2 |
+---+------------+ +---+------------+ | 2 | 1 |
| 2 | 2 |
+-----------+------------+
现在,我的问题是我不知道如何将存储为数组的数据(例如Sweets,Dessert ..)插入数据库。它总是以这个结尾:
category table
+---+------------------+
|id | name |
+---+------------------+
| 1 | Sweets, Dessert |
| 2 | |
+---+------------------+
something like that... **BUT** i want it to look like this:
category table
+---+------------------+
|id | name |
+---+------------------+
| 1 | Sweets |
| 2 | Dessert |
+---+------------------+
如何在product
,category
和product_category
表中同时插入数据?
if (mysqli_query($con, "INSERT INTO product(product_name) VALUES('$product_name')")) {
$pk1 = mysqli_insert_id($con);
if (mysqli_query($con, "INSERT INTO category(category_name) VALUES('$category_name')")) {
$pk2 = mysqli_insert_id($con);
$success = mysqli_query($con, "INSERT INTO product_category(product_id,category_id) VALUES('$pk1','$pk2')");
}
}
if ($success) {
echo "<script>alert('success')</script>";
} else {
echo "error";
}
您对我有什么建议吗?我的数据库设计还可以吗?预先谢谢你。