简体   繁体   中英

How to get data from many to many relationship table and print all rows in one line PHP

I am currently working on a library management system as a project and I have been struggling with many to many relationship tables. So, in my database, I got books, book_has_authors and authors table as shown in a picture below.

Picture of tables and relations between them

So, I have created view_books.php file where I am trying to list all the books from the database and it looks as follows:

<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>

As this is many to many relationships, one book can have many authors and many authors can have one book. In the view_books.php I have created the while loop that iterates through all books and prints them in the table. At the moment I can get all data but not the authors as the query returns multiple rows(authors) for each book. As I mentioned before I would like to list all the books in the form of HTML table. Could someone explain to me please how can I concatenate all authors for each book and print them in a single table cell next to each other? That is what I would like to achieve:

Desired output

First check this: $authors_array[] = $author_row;
(you're missing $author_row["authorsFullName"] ) .

And then you can IMPLODE $authors_array

and $stringAuthors should be used to show the output:
$stringAuthors = implode(',',$authors_array); //Author1, Author2, Author3, etc...

implode — Join array elements with a string

<?php

$array = array('lastname', 'email', 'phone');
$comma_separated = implode(",", $array);

echo $comma_separated; // lastname,email,phone

// Empty string when using an empty array:
var_dump(implode('hello', array())); // string(0) ""

?>

use the below query to get your result.

SELECT A.ISBN, A.bookTitle,  A.bookPublisher, A.bookPublicationDate, A.categoryName, GROUP_CONCAT(A.authorsFullName) AS 'Authors' FROM (
SELECT book.ISBN, book.bookTitle,  book.bookPublisher, book.bookPublicationDate, bookcategory.categoryName, `authors`.`authorsFullName`
FROM book 
INNER JOIN bookcategory ON book.bookCategory = bookcategory.categoryID 
LEFT JOIN `book_has_authors` ON book_has_authors.`book_ISBN` = book.ISBN
LEFT JOIN `authors` ON `authors`.`authorID` = `book_has_authors`.`authors_authorID`
) AS A
GROUP BY A.ISBN, A.bookTitle,  A.bookPublisher, A.bookPublicationDate, A.categoryName

Hope this will give your expected result.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM