Take random value mysql

Asked

Viewed 2,710 times

0

I would like to know some way to get some random value from Mysql without repeating, I am using this line:

$query = mysql_query("SELECT * FROM users ORDER BY RAND()");

but it repeats quite a lot of the users that I show on the screen, and if possible, if pass by the user, by id he shows no more, something like this.

  • 1

    Then it’s not random ;).

  • @rray, I thought of something like Tinder, which displays different people... Rand even works but not as I imagined...

2 answers

2

MYSQL’s RAND() Method supports SEED that forces it to generate a different random number for each SEED which will cause it to have a different order for each of them, but the same order for the same SEED.

You can use the seconds of the day for a suitable SEED.

$sql = sprintf("SELECT * FROM users ORDER BY RAND(%d)", time()%(24*60*60) );
$query = mysql_query($sql);

For minutes use use time()%(24*60)

This code will make the order always repeat at the same time of day.

How does that help? Well, it’s easier, for example, to randomly show someone a list and keep that list for as long as you want. Suppose for each user you want to show a different random list, but want the list to be the same while the user is logged in. You can use the id of this user along with some information that always changes as the number of the day for the Seed and this way during any period you will have an identity random list whenever you run the query, avoiding having to encode it in the language.

1

You can try to catch all users at once.

SELECT DISTINCT * FROM users LIMIT X ORDER BY RAND()

Where X is the number of users

Browser other questions tagged

You are not signed in. Login or sign up in order to post.