使用SQL插入表和联结表

时间:2014-12-25 16:27:10

标签: php mysql sql mysqli relational-database

我的数据库中有三个表,想要插入一些数据,但我似乎无法使其正常工作。

数据库结构(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)

我想做的是:

1-)在书表中插入一本新书。

2-)将数据插入联结表。 (包含book_id和writer_id)

3-)我不想添加新的编写者,并希望将现有的编写者添加到我的联结表中,我的编写者表包含了我想要的所有编写者。

这就是我迄今为止尝试过的事情。 ($ sqli是我的连接变量)

$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();

0 个答案:

没有答案