[SOLVED] Random Quotes

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
partiallynothing
Forum Commoner
Posts: 61
Joined: Fri Nov 21, 2003 5:02 pm
Location: connecticut, usa

[SOLVED] Random Quotes

Post 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!
User avatar
m3mn0n
PHP Evangelist
Posts: 3548
Joined: Tue Aug 13, 2002 3:35 pm
Location: Calgary, Canada

Post by m3mn0n »

I would do the randomizing and echo'ing within the while() loop.
User avatar
partiallynothing
Forum Commoner
Posts: 61
Joined: Fri Nov 21, 2003 5:02 pm
Location: connecticut, usa

Post by partiallynothing »

That returned all the entries in the database.
User avatar
partiallynothing
Forum Commoner
Posts: 61
Joined: Fri Nov 21, 2003 5:02 pm
Location: connecticut, usa

Working

Post 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']}"";
}

?>
User avatar
m3mn0n
PHP Evangelist
Posts: 3548
Joined: Tue Aug 13, 2002 3:35 pm
Location: Calgary, Canada

Post 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... :)
Post Reply