V Posted June 26, 2010 Share Posted June 26, 2010 Hello all! I wrote a script that sorts blog posts by most viewed, most commented, etc. There are no errors but for example if I have 2 posts published in the same day with the same views I would like to show the most recent one first. I tried ordering by post date and views like in the example below but it just orders by date regardless of the views and vise-versa. I'm also trying to display a message if there are no most viewed, or most commented posts. I can't think of a smart way to do all that without using a whole lot of code. Does anyone have any suggestions? :-\ if ($sort == "most_viewed") { $sql = "SELECT * FROM posts WHERE topic_id = '$topic' AND views >= 2 ORDER BY post_date, views DESC"; }//end if elseif ($sort == "most_commented") { $sql = "SELECT * FROM posts WHERE topic_id = '$topic' AND total_com > 0 ORDER BY post_date, total_com DESC"; }//end else if elseif ($sort == "high_rated") { $sql = "SELECT * FROM posts WHERE topic_id = '$topic' AND rated>=down AND up>0 ORDER BY rated, post_date DESC"; }//end else if else { //default sort $sql = "SELECT * FROM posts WHERE topic_id = '$topic' ORDER BY post_date DESC"; }//end else //result for all conditions $result = $connection->query($sql) or die(mysqli_error($connection)); while ($row = $result->fetch_assoc()) { echo "<a href=\"single_post.php?cat=$cat&topic=$topic&post=" . urlencode($row["post_id"]) . "\"> {$row["post_title"]}</a><br />"; }//end while Link to comment https://forums.phpfreaks.com/topic/205935-order-by-2-things/ Share on other sites More sharing options...
Mchl Posted June 26, 2010 Share Posted June 26, 2010 is your post_date a DATE or a DATETIME/TIMESTAMP? How about switching the columns around? $sql = "SELECT * FROM posts WHERE topic_id = '$topic' AND views >= 2 ORDER BY views DESC, post_date DESC"; Link to comment https://forums.phpfreaks.com/topic/205935-order-by-2-things/#findComment-1077636 Share on other sites More sharing options...
V Posted June 26, 2010 Author Share Posted June 26, 2010 Thanks Mchl!! Adding DESC to both seems to work I'm using DATETIME, I will eventually use a "posted ... days ago" format, if I remember correctly, I read somewhere that DATETIME is good for that. Link to comment https://forums.phpfreaks.com/topic/205935-order-by-2-things/#findComment-1077648 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.