user3177012
user3177012

Reputation: 681

PHP / MySQL Order By Date & Random

I use this code to get my results from a database using PHP:

$get_article_sql = "SELECT * FROM articles ORDER BY added DESC LIMIT 8";
$get_article_res = mysqli_query($con, $get_article_sql);
while($article = mysqli_fetch_assoc($get_article_res)){
...
}

However, what I really want to do is to randomise the results - So, I get the latest 8 articles and then randomise these results - Kind of like:

$get_article_sql = "SELECT * FROM articles ORDER BY added DESC RAND() LIMIT 8";

Obviously this gives a fetch error but is there any actual way of doing this?

Upvotes: 1

Views: 2358

Answers (3)

EternalHour
EternalHour

Reputation: 8621

EDIT: After testing, it would not randomize after first query. The more I thought about it, seems that you want to pull random records and then ORDER BY added? In this case a subquery is required.

SELECT * FROM (SELECT * FROM articles ORDER BY RAND() LIMIT 8) AS random 
ORDER BY added DESC;

New SQLFiddle

Upvotes: 0

ryvasquez
ryvasquez

Reputation: 158

Try this:

$sql = "SELECT * FROM (SELECT * FROM articles order by article_id DESC LIMIT 8) `table` ORDER BY RAND()"

Upvotes: 0

Erik
Erik

Reputation: 3636

You can either shuffle them in PHP, which is probably faster, by using shuffle($array) once you have all the results, or you can use a query but then you'd have to basically use a subquery to fetch the total results inside a query that shuffles the rest.

Something like this:

SELECT * FROM ( SELECT * FROM articles ORDER BY added DESC LIMIT 8 ) ORDER BY RAND()   

Upvotes: 3

Related Questions