Log in

View Full Version : Getting random rows from a database!



MrSheen
09-05-2007, 05:00 PM
I have like 100's of entries in a database
i was wondering if i could get like a random 3 results from the database?

Let me know.
Thanks

elwinh
09-05-2007, 05:28 PM
Maby something like this?


<?php
$result = mysql_query("SELECT id, name FROM mytable");

$row = mysql_fetch_array($result, MYSQL_NUM)) {

$num = count($row);

$random1 = rand(1, $num);
$random2 = rand(1, $num);
$random3 = rand(1, $num);

echo $row[$random1];
echo $row[$random2];
echo $row[$random3];

mysql_free_result($result);
?>

boogyman
09-05-2007, 05:33 PM
yes that is possible but you need to describe the fields in the database table.
the easiest would be to have an "id" for each record stored, and you create a script that will randomly select a number in the range then you would pull the info from that data, and repeat 2 more times

elwinh
09-05-2007, 05:36 PM
isn't that almost what the script posted above does? It only dous'nt need a id. It uses "MYSQL_NUM".

boogyman
09-05-2007, 05:44 PM
Maby something like this?


<?php

$result = mysql_query("SELECT id, name FROM mytable");

$row = mysql_fetch_array($result, MYSQL_NUM)) {

$num = count($row);

$random1 = rand(1, $num);
$random2 = rand(1, $num);
$random3 = rand(1, $num);

echo $row[$random1];
echo $row[$random2];
echo $row[$random3];

mysql_free_result($result);
?>


rather than declaring each variable explicitly, you could also do a loop to make the code more generalized and save on debug / updating


<?php
// Edit Query to specify what you wish to gather from the database
$result = mysql_query("SELECT field(s) FROM mytable WHERE condition");

$row = mysql_fetch_array($result, MYSQL_NUM)) {
$num = count($row);

$int = 3; //Number of Random Datacollections
$random = array();
for($count=0; $count<$int; $count++)
{
$random[$count] = rand(1, $num);
}

mysql_free_result($result);

// Prints out the results
foreach($random as $rand => $val)
{
echo "Result ". $rand+1 .": ". $val;
}

?>

would yield

Result 1: ______something_____
Result 2: ______something_____
Result 3: ______something_____
...
Result n+1: _____something_____

Twey
09-05-2007, 06:47 PM
There's an easier way:
SELECT * FROM mytable ORDER BY RAND() LIMIT 3;