2017-03-04 96 views
1

一個示例場景,我在mysql.i.e產品和product_images中有兩個表格,它們分別相關爲一對多關係。我想在數據庫中插入數據,它將產品表中的原始product_id與在圖像表中作爲外鍵的pro_id表相關聯,例如,product_id = 1在圖像表中具有pro_id = 1的圖像。 我完全陌生,請幫助,謝謝。如何將數據插入兩個相互關聯的表中?

回答

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) 
    " 
    ); 
} 
相關問題