SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Addict Raioo's Avatar
    Join Date
    Jul 2000
    Location
    Boston
    Posts
    212
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Unhappy hot to... pick a random row?

    Got a table of many rows. What is the fastest and less expensive way to pick a random row out of it ?

    Thanks
    I appreciate the help of everyone at SitePoint.com

  2. #2
    SitePoint Wizard bronze trophy JRMillion's Avatar
    Join Date
    Apr 2004
    Location
    Arlington VA
    Posts
    2,094
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    This is how I would do it.
    PHP Code:
    $rand_num rand(1,mysql_num_rows($result));
    for(
    $k=0;$k<$rand_num;$k++){
        
    $rand_row mysql_fetch_array($result);
    }

    //$rand_row is your random pick. 

  3. #3
    SitePoint Wizard bronze trophy JRMillion's Avatar
    Join Date
    Apr 2004
    Location
    Arlington VA
    Posts
    2,094
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    you can also do this

    PHP Code:
    $result mysql_query("SELECT * FROM table ORDER BY RAND() LIMIT 0,1");
    $row mysql_fetch_array($result); 

  4. #4
    SitePoint Addict Raioo's Avatar
    Join Date
    Jul 2000
    Location
    Boston
    Posts
    212
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by JRMillion
    you can also do this

    PHP Code:
    $result mysql_query("SELECT * FROM table ORDER BY RAND() LIMIT 0,1");
    $row mysql_fetch_array($result); 
    This works like a charm! thanks
    I appreciate the help of everyone at SitePoint.com


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •