0

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();
salep
  • 1,332
  • 9
  • 44
  • 93
  • What happens when you run this code? – Dan Bracuk Dec 25 '14 at 16:53
  • 1
    Read the manual http://php.net/manual/en/mysqli-stmt.bind-param.php `$stmt = $mysqli->prepare("INSERT INTO CountryLanguage VALUES (?, ?, ?, ?)"); $stmt->bind_param('sssd', $code, $language, $official, $percent);` - You're also not checking for errors. – Funk Forty Niner Dec 25 '14 at 16:56
  • 1
    @salep: Check for errors first. Also you should make your database explode whenever it fails: [Turning query errors to Exceptions in MySQLi](http://stackoverflow.com/q/14578243/367456) – hakre Dec 25 '14 at 16:59
  • @Dan Bracuk, here's the error I get : Warning: mysqli_stmt::bind_param(): Couldn't fetch mysqli_stmt in /Applications/MAMP/htdocs/root/kgp/book/insert.php on line 93 Warning: mysqli_stmt::execute(): Couldn't fetch mysqli_stmt in /Applications/MAMP/htdocs/root/kgp/book/insert.php on line 94 Warning: mysqli_stmt::close(): Couldn't fetch mysqli_stmt in /Applications/MAMP/htdocs/root/kgp/book/insert.php on line 95 Fatal error: Call to a member function bind_param() on boolean in /Applications/MAMP/htdocs/root/kgp/book/insert.php on line 98 – salep Dec 25 '14 at 17:02
  • I think I am getting it, will edit the question when I find the answer. – salep Dec 25 '14 at 17:13

0 Answers0