Jump to content

Help with random problem


dc_jt

Recommended Posts

Hi Im trying to pull in four random offers from the database which Ive got running fine.

 

The four are selected, therefore have featured set to 1. Each offer has a category_id so im running a random script from 1 to 4 and depending what it lands on, the specific offer is selected from the database using the category id in the switch statement below.

 

However if say for example, the random number is 2 which means the category id is 4 and there are no offers with category id 4 how do I do the random script again but excluding the 4.

 

Please see my code below.

 

Thanks

 

if(!$_GET['id']){
$total = "4";
$start = "1";

$random = mt_rand($start, $total);

$_GET['id'] = $random;
}

switch($_GET['id']){

case 1;
$iCategoryId = 1;
break;
case 2;
$iCategoryId = 4;
break;
case 3;
$iCategoryId = 3;
break;
case 4;
$iCategoryId = 6;
break;

}

$oOffer = $oTblOffers->getFeaturedHomepage($iCategoryId);

if($oOffer->title == ''){
print(here);
}

Link to comment
https://forums.phpfreaks.com/topic/93371-help-with-random-problem/
Share on other sites

The best way is to build it right into your SQL, using something like this:

SELECT * FROM table ORDER BY RAND() LIMIT 4;

 

If you can't do that, you can try something like this:

<?php
  if(!$_GET['id']){
    $total = "4";
    $start = "1";
    $oOffer = false;
    for($n=0;!$oOffer && $n < 20;$n++){ //The $n is to prevent an infinite loop
      $random = mt_rand($start, $total);
      $oOffer = $oTblOffers->getFeaturedHomepage($random);
    }
  }else{
    $oOffer = $oTblOffers->getFeaturedHomepage($_GET['id']);
  }
  if(!$oOffer)
    die("Failed to find offer");
?>

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.