I´m building a php-blog system and want to display all posts but max five from each user on the start page. I thinking of do this with a query in the database, but I´m lost on how to do that. The count() function I guess will come in handy, but can somebody help me
This is my function today, and I just whant to improve it to get max five posts from each user
protected function getAllPostsDB() {
$sql = "SELECT recipes.Recipe_ID, recipes.Title, recipes.Short_description, recipes.Step_by_step,
recipes.create_date, recipes.last_mod_date, recipes.Portions, recipes.imgPath, users.Username
FROM recipes
JOIN users
ON recipes.User_ID = users.User_ID
ORDER BY recipes.create_date DESC";
$stmt = $this->connect()->query($sql);
/* fetch all is already set to associative array*/
$result = $stmt->fetchAll();
return $result;`
If you are running MySQL 8.0, just use window functions:
This gives the last five recipes per user, as designated by column
create_date
. You can change theORDER BY
clause ofROW_NUMBER()
to some other column or set of columns if you want another sort rule.