php - Getting next and previous MySQL id according to views -
i have mysql database im saving post id, post , views. want add link next , previous post based on views.
------------------------------- | id | post | views | ------------------------------- | 1 | title 01 | 10 | | 2 | title 02 | 20 | | 3 | title 03 | 5 | | 4 | title 04 | 0 | | 5 | title 05 | 0 | | 6 | title 06 | 0 | | 7 | title 06 | 6 | -------------------------------
so try following queries. $post_id
current post id.
// previous select * posts id>'$post_id' order views asc limit 1 // next select * posts id<'$post_id' order views desc limit 1
above queries returning wrong results.
// previous select * posts views>'$views' order views asc limit 1 // next select * posts views<'$views' order views desc limit 1
those returning results until 0 occurs (from example data added above) change clause views>='$views'
(previous) , views<='$views'
(next) returns wrong results.
i know seems simple question search everywhere couldn’t find it’s easy next , previous posts according post id views doesn’t work @ all.
your time , answers highly appreciated.
edit: views column in int
bit more details.
my parent page winch call views have below query
select * posts views desc limit 10
so out put post id's 2,1,7,3,4,5,6
when user click of these posts go post display full post next , previous navigation want previous , next navigation same order parent page 2,1,7,3,4,5,6
to keep navigation less random, can add sort other field. example, id. need exact algorithm in order same results every time. example of such algorithm:
- sort posts views count in descending order.
- if 2 posts has equal views, sort these posts id in ascending order.
in case can select single, not random, next (previous) post.
-- previous post select * posts (views > '$views') or (views = '$views' , id < '$post_id') order views asc, id desc limit 1; -- next post select * posts (views < '$views') or (views = '$views' , id > '$post_id') order views desc, id asc limit 1;
also, need modify query on parent page , add sort here too:
select * posts order views desc, id asc limit 10
note:
site can used multiple users @ once. , such navigation not work in general case. example, user1 opened first post, go next (second) post. @ moment user2 opened first post , it's views count changed. if user1 goes previous page (first) now, link 'next' on may not point second page.
Comments
Post a Comment