How to insert values into a junction table? I add values into my two tables using the code below, but I also have a junction table called book_main_cover and I want to add data into this table to make a connection between book_id and metadata_image_id, how can I do it when I add the records for the first time?

With the code below, I can only add individual records without a connection.

    $stmt = $sqli-&gt;prepare("INSERT INTO book(book_original_name, book_turkish_name, book_publication_date, book_synopsis) VALUES (?,?,?,?)");
    $stmt-&gt;bind_param("ssss", $_POST['book_original_name'], $_POST['book_tr_name'], $_POST['book_year'], $_POST['book_synopsis']);
    $stmt-&gt;execute();
    $stmt-&gt;close();


    $stmt = $sqli-&gt;prepare("INSERT INTO metadata_images(metadata_image_value, type, size) VALUES (?,?,?)");
    $stmt-&gt;bind_param("sss", $name, $_FILES['book_cover']['type'], $_FILES['book_cover']['size']);
    $stmt-&gt;execute();
    $stmt-&gt;close();


I am using MySQL and InnoDB.

My database structure:

Table : book
book_id (PK)
book_original_name
book_tr_name
book_publication_date
book_synopsis

Table : metadata_images
metadata_image_id (PK)
metadata_image_value
type
size


Junction Table : book_main_cover
book_id (FK from book)
book_metadata_id (FK from metadata_images)
If I guessed correct you are using PHP PDO, so what your are looking for is this function. http://us3.php.net/manual/en/pdo.lastinsertid.php. It will return the id off the last insert tuple into the database which you can save in a variable to be used in the insert for the junction table.

$stmt = $sqli-&gt;prepare("INSERT INTO book(book_original_name, book_turkish_name, book_publication_date, book_synopsis) VALUES (?,?,?,?)");
$stmt-&gt;bind_param("ssss", $_POST['book_original_name'], $_POST['book_tr_name'], $_POST['book_year'], $_POST['book_synopsis']);
$stmt-&gt;execute();
$book_id = $stmt-&gt;insert_id;
$stmt-&gt;close();

$stmt = $sqli-&gt;prepare("INSERT INTO metadata_images(metadata_image_value, type, size) VALUES (?,?,?)");
$stmt-&gt;bind_param("sss", $name, $_FILES['book_cover']['type'], $_FILES['book_cover']['size']);
$stmt-&gt;execute();
$cover_id = $stmt-&gt;insert_id;
$stmt-&gt;close();

$stmt = $sqli-&gt;prepare("INSERT INTO book_main_cover VALUES(?,?)");
$stmt-&gt;bind_param($book_id, $cover_id);
$stmt-&gt;execute();
$stmt-&gt;close();