Thread: Order by rand()
View Single Post
Old 06-09-2008, 02:34 AM   #2 (permalink)
buggabill
The Contributor
 
buggabill's Avatar
 
Join Date: Jan 2008
Location: Maine, USA
Posts: 92
Thanks: 2
buggabill is on a distinguished road
Default

In order to get four random rows you could do something like the following:

php Code:
<?php
    // get all of the ids for a user
    $result = mysql_query("SELECT id FROM tbl_gallery WHERE fld_userid = $UserID");
   
    // get the number of rows returned
    $numrows = mysql_num_rows($result);
   
    //build an array of the ids returned
    $idarr = array();
   
    while ($row = mysql_fetch_assoc($result))
    {
        $idarr[] = $row(id);
    }

    // build an array with 4 randomly selected ids in it
    $selidarr = array();
   
    for ($i=0;$i<=4;$i++)
    {
        $selidarr[] = $idarr[rand(0,$numrows)];
    }
   
    //convert the array into a string for use in a query
    $selidstr = implode(",", $selidarr);
   
    // run one more query to get the final desired results
    $sql = "SELECT * FROM tbl_gallery WHERE $id IN ($selidstr)"
?>

Hope this helps!
__________________
-- Bill
"Why is it drug addicts and computer aficionados are both called users?" -Clifford Stoll
buggabill is offline  
Reply With Quote