- Impact
- 0


//get a random quote... using arrays.
//Be sure to connect to the db.
$query1 = "SELECT * FROM quotes";
$result1 = mysql_query($query1);
while ($row1 = mysql_fetch_array($result1))
{
$id1 = $row1['id'];
$array1[count($array1) + 1] = $id1;
shuffle($array1);
}
shuffle($array1);
//ACCESS THE RANDOM NUMBER IS BY $array1[0]
//Now we have the id of the random quote.
$random = $array1[0];
$q1 = "SELECT * FROM quotes WHERE id='$random' LIMIT 1";
$r1 = mysql_query($q1);
while ($row1 = mysql_fetch_array($r1))
{
$content = $row1['content'];
$author = stripslashes($row1['author']);
}
//Then just echo $content and $author (the person who said it) when you need it.
?>
compuXP said:Unfortunately, wouldn't rand() return any number, not just those in the db?
What happens when you run such a query? Letโs say you run this query on a table with 10000 rows, than the SQL server generates 10000 random numbers, scans this numbers for the smallest one and gives you this row. Generating random numbers is relatively expensive operation, scaning them for the lowest one (if you have LIMIT 10, it will need to find 10 smallest numbers) is also not so fast (if quote is text itโs slower, if itโs something with fixed size it is faster, maybe because of need to create temporary table).
PHP://get a random quote... using arrays. //Be sure to connect to the db. $query1 = "SELECT * FROM quotes"; $result1 = mysql_query($query1); while ($row1 = mysql_fetch_array($result1)) { $id1 = $row1['id']; $array1[count($array1) + 1] = $id1; shuffle($array1); } shuffle($array1); //ACCESS THE RANDOM NUMBER IS BY $array1[0] //Now we have the id of the random quote. $random = $array1[0]; $q1 = "SELECT * FROM quotes WHERE id='$random' LIMIT 1"; $r1 = mysql_query($q1); while ($row1 = mysql_fetch_array($r1)) { $content = $row1['content']; $author = stripslashes($row1['author']); } //Then just echo $content and $author (the person who said it) when you need it. ?>
It may not be efficient but it works![]()
while ($row1 = mysql_fetch_array($r1))
$q1 = "SELECT * FROM quotes WHERE id='$random' LIMIT 1";
$q1 = "SELECT * FROM quotes WHERE 1 LIMIT 1";
$q1 = "SELECT * FROM quotes ORDER BY rand() LIMIT 1";
$r1 = mysql_query($q1);
$row1 = mysql_fetch_array($r1);
$content = $row1['quote'];
$author = stripslashes($row1['author']);
echo "<font size=\"-1\"><i>".$content."</i><br>";
echo "<div align=right><b>".$author."</b></div></font>";


