Kaleem Shahid
Kaleem Shahid

Reputation: 61

How to insert data in two tables relating to each other?

An example scenario, I have two tables in mysql .i.e products and product_images which are related as one to many relationship (respectively). I want to insert data using a form in database which relates the original product_id from products table to pro_id table made as a foreign key in images table, for example, product_id = 1 has images with pro_id = 1 in images table. I am completely new to this, please help, thanks.

Upvotes: 1

Views: 33

Answers (1)

guesterator_php
guesterator_php

Reputation: 62

if you are using 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)
    "
    );
}

Upvotes: 1

Related Questions