I am using PHP and mySQL. I have a table of photographs. in the photographs table I have: a link to the photo, a category_id, date.
What would be the best way to list all the categories on the page with the newest 20 photos under each?
Right now I am selecting all the photos and then sorting them out after in PHP. If there gets to be 500 photos in one category this would seem very inefficient. Any better ideas for the SQL end of it?
The only other way I thought of was to loop a 20 limit query for each category, but if there are 100 categories that seems even worse!
pseudo output
[category_list] => {
[0]=> {
'category_title' => 'photos at sunset',
'posts' => {
[0] => {
'photo_link' = '1.jpg',
}
[1] => {
'photo_link' = '2.jpg',
}
}
}
[1]=> {
'category_title' => 'photos at sunrise',
'posts' => {
[0] => {
'photo_link' = '1.jpg',
}
}
}
}
pseudo code
$query =
"
SELECT
photographs.category_id, photographs.photo_link, categories.title
FROM
photographs
INNER JOIN
categories
ON
category.id = photographs.categories.id
ORDER BY
category.id DESC
";
$result = $this->pdo->prepare($query);
$result->execute();
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
$post[] = $row;
}
$result = null;
$count = sizeof($post);
//get a list of the categories
for($i=0; $i < $count; $i++) {
$categories[$i] = $post[$i]['title'];
}
$categories = array_unique($categories);
//sort categories alphabetically
sort($categories);
//add the newest 20 photos to each category
$categories_count = count($categories);
$posts_count = count($post);
for($i=0; $i < $categories_count; $i++) {
$category_list[$i]['post_count'] = 0;
for($k=0; $k < $posts_count; $k++) {
if ($categories[$i] == $post[$k]['category_title']) {
if ($category_list[$i]['count'] == 19) {
break;
}
$category_list[$i]['category_title'] = $post[$k]['category_title'];
$category_list[$i]['post'][] = $post[$k];
$category_list[$i]['post_count']++;
}
}
}