views:

35

answers:

2

My site has a library full of games, nations, game scenarios, etc.

library.php is given a type=___ & id=___

for example library.php?type=scenario&id=ABCD001

library.php saves the id to a session variable and loads an include appropriate for the type

This all works just dandy. Now, I wanted to give my users the option of pulling up a random scenario. To do that, I added a special id to the logic within lib-scenario.php (the include) such that if given library.php?type=scenario&id=random the include knows to run an alternate query for a random record rather than for the actual id

This also works just dandy... unless someone hits the Random Scenario button two+ times in a row, and decides that the previous random scenario was way cooler, I want to go back to that.

Because the http address is always directory/library.php?type=scenario&id=random no matter how many times you click Random Scenario, as soon as you click back you'll be taken to the last page with an alternate address you visited.

So, if you start at the Home page, and hit Random Scenario 35 times, then decide the 34th one was what you wanted and click BACK, you'll be put back onto the Home page.

I must admit this was not a problem I had anticipated. One of my testers was the first to have the urge to back-up in the random scenario stream and here we are.

How can I add back-up functionality to my script?

+1  A: 

Make the 'Random Scenario' button simply link to an actual (but random) scenario id. You'll probably have to construct this with an SQL query to get all the id's of your scenarios.

$result = mysql_query("SELECT id FROM scenarios");
while ($row = mysql_fetch_row($result)) {
    $ids[] = $row[0];
}
$randomid = array_rand($ids);

Button:

<a href="directory/library.php?type=scenario&id=<?php echo $randomid; ?>Random Scenario</a>

If your scenario id's are all consecutive numbers you can simply use this instead:

$randomid = rand($min, $max);
Lotus Notes
Aren't we clever? I *do* like that! Thank you Byron!
Andrew Heath
excellent solution!
At first I thought that "SELECT id FROM scenarios ORDER BY RAND() LIMIT 1" would have been easier, but it turns out that it's also randomly ordering ALL the rows in the table before selecting one, which would be extremely slow for large tables.
Lotus Notes
+1  A: 

you can resolve this by redirecting to the canonical url for the scenario, i.e.: id=random redirects to id=A92831 or whatever was selected. the final url will be stored in the history, rather than the id=random url.

I was wondering if a redirect would work. I can drop Byron's answer right into my code in less than a minute, though, so he gets the check. Thank you for responding jxac!
Andrew Heath
A redirect would still require an SQL query (which I'm pretty sure you can't do in an .htaccess file) to find out which id's are valid.
Lotus Notes