Php 如何在两个相互关联的表中插入数据?
在一个示例场景中,我在mysql中有两个表,即products和product_images,它们分别作为一对多关系进行关联。我想使用数据库中的一个表单插入数据,该表单将products表中的原始product_id与作为images表中外键的pro_id表关联起来,例如,product_id=1在images表中具有pro_id=1的图像。Php 如何在两个相互关联的表中插入数据?,php,mysqli,Php,Mysqli,在一个示例场景中,我在mysql中有两个表,即products和product_images,它们分别作为一对多关系进行关联。我想使用数据库中的一个表单插入数据,该表单将products表中的原始product_id与作为images表中外键的pro_id表关联起来,例如,product_id=1在images表中具有pro_id=1的图像。 我对这个完全陌生,请帮忙,谢谢 如果您正在使用mysqli $connection = mysqli_connect(your database
我对这个完全陌生,请帮忙,谢谢 如果您正在使用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)
"
);
}