Jump to content

randomising 4 records


gerkintrigg

Recommended Posts

Okay, i have to admit defeat on this one...

I'm building a new website (http://www.cornwalldevon.co.uk) and I'm trying to get the adverts to randomise. I don't want the same advert to appear more than once on the page and I want a maximum of 4 adverts per page.

 

I also want to filter the results by area... but some pages don't have an area variable to parse to the randomiser script... Is this getting too confusing yet?

 

Anyway- I've tried this:

$q="SELECT COUNT(*) as `records` FROM `advertisers` WHERE `area`='$location'";
$sql=@mysql_query($q);			
$result=@mysql_result($sql,0);
$rand= rand(1, $result);

So that gets the number of records in the database and works out a random variable based on it, so I suppose the random variable relates to the position of the record in the array.

 

Perhaps I'm just very tired, but I have no idea how to use this random variable to actually print out up to 4 different image adverts. I have tried incrementing the random variable, but when it gets to the maximum number, it stops (because it runs out of records).

 

I can (in theory) work out various ways, but all of them are code heavy.

 

Any suggestions? (oh dear I hope that makes sense!!)

Thanks,

Neil (very desperate and needing a bed)

Link to comment
https://forums.phpfreaks.com/topic/114576-randomising-4-records/
Share on other sites

My usual method is

 


$adverts = array ('a.jpg', 'b.jpg', 'c.jpg', 'd.jpg', 'e.jpg');

shuffle ($adverts )                                     // shake the bag

$selection = array_slice ($adverts , 0, 4);     // pull 4 random adverts out of the bag 

SELECT whatever FROM tablename ORDER BY RAND()

 

pulls from db in random order

 

An advantage of array_slice is you can store the array in a session var and on first page

array_slice($array, 0, 4)              // first 4

then on next page

array_slice($array, 4, 4)             // next 4, etc

without duplicating adverts until you reach the end and start again

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.