【问题标题】:How to insert data in two tables relating to each other?如何在两个相互关联的表中插入数据?
【发布时间】:2017-03-05 13:29:06
【问题描述】:

一个示例场景,我在 mysql 中有两个表,即 products 和 product_images,它们以一对多关系(分别)相关。我想使用数据库中的表格插入数据,该表格将 products 表中的原始 product_id 与作为图像表中的外键制作的 pro_id 表相关联,例如,product_id = 1 在图像表中具有 pro_id = 1 的图像。 我对此完全陌生,请帮助,谢谢。

【问题讨论】:

    标签: php mysqli


    【解决方案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)
        "
        );
    }
    

    【讨论】:

      猜你喜欢
      • 2013-09-15
      • 1970-01-01
      • 1970-01-01
      • 2015-01-29
      • 1970-01-01
      • 2020-11-27
      • 2014-05-06
      • 2017-11-28
      相关资源
      最近更新 更多