PHP How to pick a random value like Rand($min, $max) but with a query?

Asked

Viewed 166 times

1

For example, in a browser game I want when the user clicks attack to return another user who has +- the same battle power as him.

$select = $mysqli->query("select * from data order by rand()");

That way it always returns me a random value, but what I want is a value between x and y... something like Rand($min, $max), but from what I saw, the order by rand doesn’t work that way...

Someone give me a light on how to do this?

1 answer

1


Where [min] is the minimum number and [max] maximum.

$select = $mysqli->query("select * from data order by rand() LIMIT [max], [min]");

This query is slow because the LIMIT will make a Sort, an interesting link about the performance of random record selection: http://jan.kneschke.de/projects/mysql/order-by-rand/

An alternative, where id is a unique numeric key:

$select = $mysqli->query("select * from data where id between [min] and [max] order by rand()");
  • Great, thanks João! + 1

Browser other questions tagged

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