I have three tables in my database and want to insert some data, but I can't seem to make it work.
Database structure (mysql & InnoDB)
book
book_id (AI & Primary Key)
book_original_name
writer
writer_id (AI & Primary Key)
writer_name
book_who_wrote_it
book_id (Foreign Key from book table)
writer_id (Foreign Key from writer table)
What I am trying to do is:
1-) Insert a new book into book table.
2-) Insert data into junction table. (contains book_id and writer_id)
3-) I don't want to add new writers and want to add existing writers into my junction table, my writer table contains all writers I want.
And here's what I've tried so far. ($sqli is my connection variable)
$add_book_original_name = htmlspecialchars($_POST['book_original_name']);
$add_book_original_name = mysqli_real_escape_string($sqli, $add_book_original_name);
$stmt = $sqli->prepare("INSERT INTO book(book_original_name) VALUES (?)");
$stmt->bind_param("s", $add_book_original_name);
$stmt->execute();
$stmt->close();
// junction table stuff
$get_book_id = $sqli->insert_id; // I am trying to get the last inserted book id
$get_writer_id = $sqli->prepare("SELECT writer_id FROM writer WHERE writer_name = $add_book_writer_name ");
$stmt->bind_param("i", $get_writer_id);
$stmt->execute();
$stmt->close();
$stmt = $sqli->prepare("INSERT INTO book_who_wrote_it(book_id, writer_id) VALUES($get_book_id, $get_writer_id)");
$stmt->bind_param("ii", $get_book_id, $get_writer_id);
$stmt->execute();
$stmt->close();