Master-Detail using PHP PDO
I'm stuck trying to create a result page that lists details based on a series of masters.
Here's a sample problem...
Three tables such as those shown below:
Book (id, title)
Author (id, name)
BookAuthors (bookID, authorID)
I wish to generate a list similar to this:
Book Title 1
Author 1
Author 2
Book Title 2
Author 3
Book Title 3
Author 1
Author 4
and so on.
I wish to use PHP PDO开发者_高级运维 to achieve this.
[Updated with more detail]
The problem I have is more about how to go about traversing the results from the PDO when nesting prepared statements is not possible...
I was hoping to nest a query within a query and use the results from the 1st query [I've extended the query to include a filter on the book titles, but this may be blank thus returning the whole set]:
select id as idBook,title from book where title like %:title%
to then create the list of authors for each book
select name from author, bookauthors
where bookauthor.authorid = author.id
AND bookauthor.bookid = :idBook:
Where :idBook: is the next book id from the result set from the 1st query.
As the number of books retrieved in the 1st query may be large, I was hoping not to use fetchall if possible...
Anyone got pointers / sample solution code for this?
many thanks in advance!
Instead of multiple queries I'd rather store some state in a php variable. In this case all you need to know is: has the book "changed", i.e. must the script print the title?
<?php
$pdo = new PDO('mysql:host=localhost;dbname=test', 'localonly', 'localonly', array(PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION));
foo($pdo); // add test data
$r = $pdo->query('
SELECT
l.bookID, b.title, a.name
FROM
BookAuthor as l
JOIN
Author as a
ON
a.id=l.authorID
JOIN
Book as b
ON
b.id=l.bookID
ORDER BY
l.bookID,
l.authorID
');
$currentBook = null;
foreach($r as $row) {
if ( $currentBook!=$row['bookID'] ) {
echo $row['title'], "\n";
$currentBook=$row['bookID'];
}
echo ' ', $row['name'], "\n";
}
function foo($pdo) {
$pdo->exec('create temporary table Book (id int auto_increment, title varchar(48), primary key(id))');
$pdo->exec('create temporary table Author (id int auto_increment, name varchar(48), primary key(id))');
$pdo->exec('create temporary table BookAuthor (bookID int, authorID int)');
$pdo->exec("INSERT INTO Author (id,name) VALUES (1,'Author1'),(2,'Author2'),(3,'Author3'),(4,'Author4')");
$pdo->exec("INSERT INTO Book (id,title) VALUES (1,'Book Title 1'),(2,'Book Title 2'),(3,'Book Title 3')");
$pdo->exec("INSERT INTO BookAuthor (bookID,authorID) VALUES (1,1),(1,2),(2,3),(3,1),(3,4)");
}
精彩评论