【发布时间】:2020-02-04 10:12:09
【问题描述】:
我目前正在将图书馆管理系统作为一个项目工作,并且一直在努力处理多对多的关系表。因此,在我的数据库中,我得到了书籍、book_has_authors 和 authors 表,如下图所示。
Picture of tables and relations between them
所以,我创建了 view_books.php 文件,我试图在其中列出数据库中的所有书籍,它看起来如下:
<table class="table table-hover">
<!-- table table-striped table-bordered table-hover begin -->
<thead>
<!-- thead begin -->
<tr>
<!-- tr begin -->
<th scope="col"> ISBN: </th>
<th scope="col"> Book Title: </th>
<th scope="col"> Publisher: </th>
<th scope="col"> Publication Year: </th>
<th scope="col"> Category: </th>
<th scope="col"> Number of copies: </th>
<th scope="col"> Edit: </th>
<th scope="col"> Delete: </th>
</tr><!-- tr finish -->
</thead><!-- thead finish -->
<tbody>
<!-- tbody begin -->
<?php
$i = 0;
$get_books = "SELECT book.ISBN, book.bookTitle, book.bookPublisher, book.bookPublicationDate, bookcategory.categoryName FROM book INNER JOIN bookcategory ON book.bookCategory = bookcategory.categoryID ";
// $get_payments = "SELECT * FROM books";
$run_books = mysqli_query($conn, $get_books);
while ($book_row = mysqli_fetch_array($run_books)) {
$ISBN = $book_row['ISBN'];
$title = $book_row['bookTitle'];
$publisher = $book_row['bookPublisher'];
$pubdate = $book_row['bookPublicationDate'];
$cat_name = $book_row['categoryName'];
// get total number of copies for each book
$count_copies = "SELECT * FROM bookcopy WHERE ISBN = $ISBN ";
$run_count = mysqli_query($conn, $count_copies);
$copy_num = mysqli_num_rows($run_count);
// get all authors
$authors_array = array();
$get_authors = "SELECT author.authorsFullName FROM book INNER JOIN book_has_authors ON book_has_authors.book_ISBN = book.ISBN INNER JOIN author ON author.authorID = book_has_authors.authors_authorID WHERE ISBN=$ISBN;";
$run_authors = mysqli_query($conn, $get_authors);
while($author_row = mysqli_fetch_array($run_authors)){
$authors_array[] = $author_row;
}
$i++;
echo '<tr scope="row"><!-- tr begin -->
<td>' . $ISBN . '</td>
<td>' . $title . '</td>
<td>' . $publisher . '</td>
<td>' . $pubdate . '</td>
<td>' . $cat_name . '</td>
<td>' . $copy_num. '</td>
<td><a href="index.php?delete_product' . $ISBN . '>
<i class="fas fa-trash"></i> Delete
</a>
</td>
<td>
<a href="index.php?edit_product' . $ISBN . '>
<i class="fa fa-pencil"></i> Edit
</a>
</td>
</tr><!-- tr finish -->
';
}
?>
</tbody><!-- tbody finish -->
</table>
由于这是多对多关系,所以一本书可以有多个作者,而许多作者可以有一本书。在 view_books.php 中,我创建了循环遍历所有书籍并将它们打印在表格中的 while 循环。目前我可以获取所有数据,但不能获取作者,因为查询为每本书返回多行(作者)。正如我之前提到的,我想以 HTML 表格的形式列出所有书籍。有人可以向我解释一下如何连接每本书的所有作者并将它们打印在彼此相邻的单个表格单元格中吗?这就是我想要实现的目标:
【问题讨论】:
-
您似乎已经在数组中包含了这本书的作者姓名 - 所以只需
implode然后......? -
而且,FWIW,我的偏好是 id 在数据库范围之外应该没有任何意义,所以我会在 ISBN 旁边存储一个单独的代理 id。