I’m trying to do a simple search query in php with:
SELECT * FROM `books` NATURAL JOIN `authors` WHERE `books`.`title` LIKE '%$search%
In the returned result I expect the same book title to have more then one author. I would like to display the title just once with multiple authors, and can’t seem to find an elegant solution to print the wanted values without doing at least 2 loops with multiple counters like so:
$last = ""; $i = 0;
while ($row = $result->fetchRow(MDB2_FETCHMODE_ASSOC)) {
$current = $row['title'];
if ($current != $last) {
$i += 1;
$books[$i]['title'] = $current;
$books[$i]['author'][] = $row['author'];
$books[$i]['pages'] = $row['pages'];
} else {
$books[$i]['author'][] = $row['author'];
}
$last = $current;
}
foreach ($books as $book) {
$return_result .= 'Title: ' . $book['title'] . '<br />';
foreach ($book['author'] as $author) {
$return_result .= 'Author: ' . $author . '<br />';
}
$return_result .= 'Pages: ' . $book['pages'] . '<br />';
$return_result .= '<br />';
}
Please tell me if there’s a better way to do this, maybe in MySQL ?
The GROUP_CONCAT function will give a delimited list of authors.