如何将数据插入两个相互关联的表中?
问题描述:
一个示例场景,我在mysql.i.e产品和product_images中有两个表格,它们分别相关为一对多关系。我想在数据库中插入数据,它将产品表中的原始product_id与在图像表中作为外键的pro_id表相关联,例如,product_id = 1在图像表中具有pro_id = 1的图像。 我完全陌生,请帮助,谢谢。如何将数据插入两个相互关联的表中?
答
如果您使用的mysqli
$connection = mysqli_connect(your database information);
//from the form create the main record insert statement into mysql
mysqli_query($connection,
"INSERT INTO yourtable
(fields)
VALUES
(values)
");
//get the id of that record you just inserted
$id = mysqli_insert_id($connection);
// get the images from the form
$images = $_POST['images'];
//this is assuming your images are sent as an array of images from the form, would be slightly different if there is only one.
foreach($images as $image){
mysqli_query($onnection,
"INSERT INTO images_table
(product_id, all other fields)
VALUES
($id, all other values)
"
);
}