插入到主表具有特定ID的联结表中

时间:2014-12-26 16:35:36

标签: php sql mysqli relational-database

有点难以解释,我会尽力而为。我正在使用MySQL和InnoDB。

当我添加具有相同名称的第二本书时,我无法将其ID添加到book_who_wrote_it表中。第一个ID被添加。这就是问题所在。

我有一个名为book_who_wrote_it的表。它包含writer_id和book_id。让我们说我有一本名为" Metamorphosis"的书。当我添加具有相同名称的第二本书时,即使它们在book_id表中具有不同的ID,第一本书的ID也会被添加到book_who_wrote_it。

如果有多个同名书籍,book_who_wrote_it表中的book_id将获得第一个book_id。

这是我的表结构

book
book_id (PK & AI)
book_original_name
book_synopsis

writer
writer_id (PK & AI)
writer_name

book_who_wrote_it
book_id (FK from book table)
writer_id (FK from writer table)

这是我的代码。

$add_book_writer_name = $_POST['book_writer_name'];
$add_book_original_name = $_POST['book_original_name'];
$add_book_synopsis = $_POST['book_synopsis'];

$writer_id = "SELECT writer_id FROM writer WHERE writer_name = '$add_book_writer_name'";
$writer_result = $sqli->query($writer_id);
$writer_row = $writer_result->fetch_assoc();
$writer_finish = $writer_row['writer_id'];

$book_id = "SELECT book_id FROM book WHERE book_original_name = '$add_book_original_name' AND book_synopsis = '$add_book_synopsis'";
// I am trying to get book name and synopsis to make sure I get the right book id, 
// but I can't make it work.
$book_result = $sqli->query($book_id);
$book_row = $book_result->fetch_assoc();
$book_finish = $book_row['book_id'];

$stmt = $sqli->prepare("INSERT INTO book(book_original_name, book_synopsis) VALUES(?,?)");
$stmt->bind_param("ss", $add_book_original_name, $add_book_synopsis);
$stmt->execute();

$who_wrote_it = $sqli->prepare("INSERT INTO book_who_wrote_it(book_id, writer_id) VALUES(?,?)");
$who_wrote_it->bind_param("ii", $book_finish, $writer_finish);
$who_wrote_it->execute();

那么如何将第二个ID添加到book_who_wrote_it表中,即使这两本书的名称相同?

1 个答案:

答案 0 :(得分:0)

好的,我解决了。

除了查询的顺序之外,代码没有任何问题。我试图在插入之前从数据库中选择一条记录,这就是问题所在。