开发者

SQL Result Random loop through

I have a SQL database that contains a field. I can get all of the elements in that field by:

      $result=mysql_query($sql);
      while($row=mysql_fetch_array($result)){
         $ftype  =$row['ftype']; //name of field is 'ftype'
         print $ftype}  //do something  

I want a random element to be printed out each time the page is opened/refreshed.

Knowing that the result is an array containing the information i want, I want to randomly choose an element of the array. Also, if there are N elements in the array, I want to choose all N elements exactly once before I show any element again for second time. The process repeats itself. I know how to code something like this in java or python, but I don't think that's the way I should go.

I think I need to use javascript, but I'm just not sure what technology to use.

UPDATE:

Patrick's 开发者_StackOverflowidea seems to be exactly what i was looking for. I thought I would share what I have now and maybe you can suggest optimization. I hope the intent in the code is obvious.

<?
session_start();
if (!isset($_SESSION['count']) || !isset($_SESSION['randomArray'])) {
      $count = 0;
      $randomArray = array();
      $sql="SELECT youtubeurl FROM Foodlist";
      $result=mysql_query($sql);
      while($row=mysql_fetch_array($result)){
           array_push($randomArray,$row['youtubeurl']);
      }
      shuffle($randomArray);
      $_SESSION['randomArray'] = $randomArray;
      $_SESSION['count'] = $count; 
} elseif ($_SESSION['count'] >= sizeof($_SESSION['randomArray'])){
   $_SESSION['count'] = 0;
   $randomArray = $_SESSION['randomArray'];
   shuffle($randomArray);
   $_SESSION['randomArray'] = $randomArray;
} else{
   $randomArray = $_SESSION['randomArray'];
   $count = $_SESSION['count'];
   echo $randomArray[$count];
   $_SESSION['count']++;
}
?>


You can do this without Javascript, however you'll need to open/maintain a session.

Pseudocode:

data = data_from_mysql()

choice = random.choice(data, exclude = SESSION['choices'])
SESSION['choices'].append(choice)

print choice

if len(SESSION['choices']) == len(data):
    SESSION['choices'] = []


If you want a random result let the dbms take care of it. Add this to the bottom of your sql query.

ORDER BY RAND()
LIMIT 1
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜