Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/240.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何在两个相互关联的表中插入数据?_Php_Mysqli - Fatal编程技术网

Php 如何在两个相互关联的表中插入数据?

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

在一个示例场景中,我在mysql中有两个表,即products和product_images,它们分别作为一对多关系进行关联。我想使用数据库中的一个表单插入数据,该表单将products表中的原始product_id与作为images表中外键的pro_id表关联起来,例如,product_id=1在images表中具有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)
    "
    );
}