Jump to content

Select random records and holding for pagination


Recommended Posts

Hi,

 

I'm building a business directory. When a user searches for a business I want the results to display randomly, as it would be unfair to order by date or alphabetically.

 

This is simple enough. Except I need to be able to save the random selection for pagination. This way there is no repeat of records and the user can view all the records available.

 

Is this possible? And if so, can anyone help with some strategies?

 

Thanks.

The only ways I could think of this being possible is to

 

A: create a table for searches which holds the id's of that particular search in order they were selected. So basically when the search is initially done a new record is inserted into that table (the searchid can be appended using GET or session) then just access that table for the next set of ID's to query.

 

B: Store the id's in session instead of in a table.

 

The advantage of storing them in a search table, is you can say "recently searched" and display those results for SEO stuff. The upside to the session, a lot less work as all you need is one session variable with searchedids stored in it and just access them.

 

At least thats the theory behind them, good luck.

This is the solution I got working for anyone wanting to know:

 

Generate a random number in PHP, store it in a session variable, and finally use it in the MySQL query inside the RAND parenthesis. Therefore the random number used every time is the same for the visitor session, and the global order will stay the same in the different pages.

 

The PHP code to generate and store the random number:

 

$rand = $_SESSION['rand'];
if (empty($rand)) {
  srand((float)microtime()*1000000);
  $rand = rand();
  $_SESSION['rand'] = $rand;
}

 

Open the session with session_start() at the top of the PHP script.

 

Finally the MySQL query becomes something like this:

 

SELECT * FROM user LIMIT 20,10 ORDER BY RAND($rand)

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.