Jump to content

ORDER BY 2 things


V

Recommended Posts

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
Share on other sites

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
Share on other sites

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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.