Page 1 of 1

[SOLVED] Random Quotes

Posted: Fri Nov 28, 2003 12:38 pm
by partiallynothing
I followed a tutorial on this and came out with non-working code.

My code:

Code: Select all

<?php
echo "<b><u>Q u o t e s</u></b><BR><BR>";
$query = "SELECT firstname, lastname, pretext, text FROM quotes";
$result = mysql_query($query) or die (mysql_error());
while($row = mysql_fetch_array($result)){
    $row_array[] = "{$row['firstname']} {$row['lastname']}, {$row['pretext']}<BR>"{$row['text']}"";
}
$random_row = $row_array[rand(0, count($row_array) - 1)];
echo $random_row;
?>
Can anyone figure out what I'm doing wrong?! Thanks!

Posted: Fri Nov 28, 2003 12:42 pm
by m3mn0n
I would do the randomizing and echo'ing within the while() loop.

Posted: Fri Nov 28, 2003 12:44 pm
by partiallynothing
That returned all the entries in the database.

Working

Posted: Fri Nov 28, 2003 12:49 pm
by partiallynothing
I got it to work, and it's much simpler now:

Code: Select all

<?php
echo "<b><u>Q u o t e s</u></b><BR><BR>";
$query = "SELECT firstname, lastname, pretext, text FROM quotes ORDER BY rand()";
$result = mysql_query($query) or die (mysql_error());
while($row = mysql_fetch_array($result)){
    echo "{$row['firstname']} {$row['lastname']}, {$row['pretext']}<BR>"{$row['text']}"";
}

?>

Posted: Fri Nov 28, 2003 12:57 pm
by m3mn0n
MySQL Manual wrote: From version 3.23 you can do: SELECT * FROM table_name ORDER BY RAND() This is useful to get a random sample of a set SELECT * FROM table1,table2 WHERE a=b AND c<d ORDER BY RAND() LIMIT 1000. Note that a RAND() in a WHERE clause will be re-evaluated every time the WHERE is executed. RAND() is not meant to be a perfect random generator, but instead a fast way to generate ad hoc random numbers that will be portable between platforms for the same MySQL version.
There is many ways to do this, but here is one I like... :)