I'm in the early stages of setting some functionality to control pagination of some image board components with PHP/MySQL.
What I need to do initially is set the LIMIT
and OFFSET
clauses only on the boards
table part of the query. This is so I can paginate by boards displayed.
The images that appear on the boards (4 per board) are controlled by a counter inside a while
loop when this data is outputted, so it is important that no LIMIT or OFFSET is applied to those.
The data is fetched with one query to prevent doing nested MySQL calls to the database which would be a performance problem.
There are 3 tables at play in the MySQL below - a boards
table, an images
table, and a boards_images
table that is a pivot/linking table with a many-to-many relationship that stores the images that are allocated to the boards.
Question
In the following function, how would I set it so the LIMIT
and OFFSET
clauses only apply to the boards
table. I can't work out if I need to group the data, or do a subquery, neither of which I have done before, or if the solution is neither of those approaches?
function boardsOutput($limit=0, $offset=0) {
$s = "SELECT boards.board_name, boards.board_id, boards.user_id, images.filename开发者_如何学编程, images.image_title
FROM boards
LEFT JOIN boards_images ON boards_images.board_id = boards.board_id
LEFT JOIN images ON boards_images.image_id = images.image_id
WHERE boards.user_id = :user_id
ORDER BY boards.board_id DESC";
// append the LIMIT and OFFSET values onto the query
if($limit > 0) {
$s.= " LIMIT " . $limit;
}
if($offset > 0) {
$s.= " OFFSET " . $offset;
}
return $s;
}
// Provide values for the $limit and $offset arguments
$queryString = boardsOutput($limit, $offset);
// then add the $queryString variable to a PHP PDO prepare() method etc
Any help hugely appreciated.
精彩评论