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
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
Maby something like this?
PHP Code:<?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);
?>
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
Last edited by boogyman; 09-05-2007 at 05:36 PM. Reason: // sorry I am a slow typer... elwinh beat me to it
isn't that almost what the script posted above does? It only dous'nt need a id. It uses "MYSQL_NUM".
rather than declaring each variable explicitly, you could also do a loop to make the code more generalized and save on debug / updating
would yieldPHP Code:<?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;
}
?>
Result 1: ______something_____
Result 2: ______something_____
Result 3: ______something_____
...
Result n+1: _____something_____
Last edited by boogyman; 09-05-2007 at 05:51 PM. Reason: added comments
There's an easier way:Code:SELECT * FROM mytable ORDER BY RAND() LIMIT 3;
Twey | I understand English | 日本語が分かります | mi jimpe fi le jbobau | mi esperanton komprenas | je comprends français | entiendo español | tôi ít hiểu tiếng Việt | ich verstehe ein bisschen Deutsch | beware XHTML | common coding mistakes | tutorials | various stuff | argh PHP!
Bookmarks