Re: [PHP3] Ordering MySQL query ORDER by Random
| From: | (Richard Lynch) | Date: | Fri, 09 Jun 2000 22:10:25 +0000 |
| Subject: | Re: [PHP3] Ordering MySQL query ORDER by Random | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-1468@lists.php.net to get a copy of this message | ||
In article <393E61A9.8D62D802@billtron.com>, bill@billtron.com (bill) wrote:
> It appears that my version of MySQL doesn't allow a SELECT statement to
> ORDER BY RAND.
>
> So, the question is, how to do it in PHP?
>
> I have found out how to select any -one- item at random thusly:
>
> --------------------------------------------
> $sql="SELECT * FROM $tablename";
> $end=mysql_query($sql);
> $num=mysql_num_rows($end);
for ($i = 0; $i < $num; $i++){
$rows[] = $i;
}
shuffle($rows);
> mt_srand((double)microtime()*1000000);
> $randrow = mt_rand( 1, $num);
>
//> mysql_data_seek($end, $randrow-1);
>
> $result2=mysql_fetch_array($end);
> // display components from this row here . . .
> ----------------------------------------------
>
> I thought of just running a loop, but, I can't, it will just pick
> another row at random, possibly picking the same row again.
If shuffle is undefined (PHP is old) then you'll have to write your own:
function shuffle(&$array){
//Assume mt_srand() already called.
for ($i = count($array) - 1; $i > 0; $i--){
$randrow = mt_rand(1, $i);
$temp = $array[$i];
$array[$i] = $array[$randrow];
$array[$randrow] = $temp;
}
return $array;
}
--
Richard Lynch | If this was worth $$$ to you, buy a CD
US Customer Support Director | from one of the artists listed here:
Zend Technologies USA | http://www.L-I-E.com/artists.htm
http://www.zend.com | (this has nothing to do with Zend,
duh!)