Zerium
Zerium

Reputation: 17333

How to select a set of random rows from a table based on a key?

I know about the RAND() function in SQL to select random rows from a table, but the problem is I don't want it selecting different random rows each time I refresh the browser. I want the same set of random rows, which is selected based on a key.

For example, say this is my table:

----------------------
| id | word | literal|
----------------------
|  1 | say  |   YAS  |
----------------------
|  2 | eat  |   TAE  |
----------------------
|  3 | hit  |   TIH  |
----------------------
|  4 | bad  |   DAB  |
----------------------
|  5 |delve | EVLED  |
----------------------

maybe if the key was 6, it would select rows 4 & 5 every time. But maybe if the key was 3, it would select rows 2 and 5. So it would select a set of random rows each time based on a key.

Is this possible?

Upvotes: 0

Views: 189

Answers (3)

SomeKittens
SomeKittens

Reputation: 39532

Good thought with the md5 hash, but there's a much easier way to do it. Generate your random number however you want and the use the $_SESSION superglobal to store the number.

Example:

session_start();
if(!isset($_SESSION["randomNumber"])){
    $_SESSION["randomNumber"] = generateRandomQuery();
}

You'd then be able to use the number when you build your query. Using PDO, it'd be like this:

$number = $_SESSION["randomNumber"];
$query = $database->prepare("SELECT id FROM *databaseName* where id = :id");
$query->execute(array(":id" => $number));

Upvotes: 1

Razvan
Razvan

Reputation: 10093

You can use the : Rand(N) form of the MySQL function and take care to pass the same N each time you want the same sequence of generated random numbers. The N could stay the same during a specific session or it could be stored in a cookie for use over a longer period. It depends on how long you need the sequence to remain the same.

Upvotes: 4

J A
J A

Reputation: 1766

An idea..

Save the row id in SESSION/cookie,

$var = value from $_SESSION/cookie
if (isset($var)){

   $sql = select RAND...

} else {

   $sql = select ..... where row = $var

}

Upvotes: 0

Related Questions