Reputation: 1380
My question is a little bit long, I am sorry for that.
I add values into my two tables using the code below, but I also have a junction table called book_cover and I want to add data into this table to make a connection between book_id and metadata_image_id (since a book has more than one cover images), how can I do it when I add the records for the first time?
I couldn't make the connection even though I read about joins.
I am using MySQL and InnoDB.
Here is my PHP code to add data:
$stmt = $sqli->prepare("INSERT INTO book(book_original_name, book_publication_date, book_synopsis) VALUES (?,?,?,?)");
$stmt->bind_param("sss", $_POST['book_original_name'], $_POST['book_year'], $_POST['book_synopsis']);
$stmt->execute();
$stmt->close();
$stmt = $sqli->prepare("INSERT INTO metadata_images(metadata_image_value, type, size) VALUES (?,?,?)");
$stmt->bind_param("sss", $name, $_FILES['book_cover']['type'], $_FILES['book_cover']['size']);
$stmt->execute();
$stmt->close();
For instance, when I added the book that has the id of 50 and metadata_image has the id of 92, I also want to add book_id and metadata_image_id to my junction table to create the relation between a particular book and image. What kind of SQL query should I use to achieve that?
My database structure:
Table : book
book_id (PK and AI)
book_original_name
book_publication_date
book_synopsis
Table : metadata_images
metadata_image_id (PK and AI)
metadata_image_value
type
size
Junction Table : book_cover
book_id (Foreign key from book)
book_metadata_id (Foreign key from metadata_images)
Upvotes: 1
Views: 2407
Reputation: 8595
If you know that you just inserted the book with ID 50 and the image with ID 92, and these are directly related (i.e., that book has that image on its cover), then the query to populate the junction table is simply:
INSERT INTO book_cover VALUES (50, 92);
There is no secret or special query for junction tables. The trick is efficiently determining which values to insert; for that, use MySQL's LAST_INSERT_ID()
function, which you can access via the mysqli API as mysqli::$insert_id
.
You must get the ID immediately following the INSERT
statement that generated it, in the same session. You can save it in a user variable, perform the next insert, and then use the insert ID from the second table along with the ID saved from the first table as the parameters for your insert to the junction table.
It's a good idea to wrap all of this in a transaction so that you don't end up inserting only part of a book's information; either all three queries (or however many) should succeed, or all should fail.
Upvotes: 2