Jump to content

Non repeating, random entry MySql Querys ?!?!?


PHP Learner

Recommended Posts

Hello coders,

 

I'm using this code to grab random results from a table and it works well but I need it to be a non-repeating event.

 

$offset_result = mysql_query( " SELECT FLOOR(RAND() * COUNT(*)) AS `offset` FROM `jobs_board` ");
$offset_row = mysql_fetch_object( $offset_result );
$offset = $offset_row->offset;

 

I'm using this query followed by the html which is a set of divs with inline echo statements for the various variables I've localised from the table. Then I'm repeating that process a number of times to create a small list (I wanted to use a single while loop but cant figure it out at the moment).  Anways, how can I make it so each query is random but also not repeated? At the moment they are indeed random but sometimes one same entry will appear a number of times consecutively...

 

Nice one guys, L-plate

Link to comment
Share on other sites

You only have to look at the total number of records in the table, and them do a rand() between 0 and the resulting number of records.

So if you add more records, the rand() funtion will include them, and so on.

 

// $Limit =  total number of records ;
SELECT * FROM table_name ORDER BY RAND() LIMIT $Limit ;

Link to comment
Share on other sites

Thanks very much, but, the guy that wrote the above code saysabout the rand()..

 

"The problem with this method is that it is very slow. The reason for it being so slow is that MySQL creates a temporary table with all the result rows and assigns each one of them a random sorting index."

 

My table is gonna become massive, with thousands of entries so I chose this method to overcome snags in the future. Not sure if this is correct but others who commented on the page seem to agree.  Is there anyway of adapting the code to counter repeating entries? Or something you can do with PHP?

 

Cheers, pLate

Link to comment
Share on other sites

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.