Jump to content

[SOLVED] randomly select 3 of n records


programguru

Recommended Posts

does anyone have an idea on selecting random records.. my code is working fine as is.

 

as you can see my mysql query is limited to 3 WHERE featured=1, but it's possible i will have 20-30 featured records.

 

i tried variations of php rand() and its family with no luck..

 

any ideas?

 

 ... $sql = "SELECT id, date_added, date_start, date_end, title, spaw1, featured FROM $table_name WHERE featured=1 ORDER by date_added LIMIT 3";

$result = mysql_query($sql) or die(mysql_error());

while ($row = mysql_fetch_array($result)) {
		$id = $row['id'];
		$date_added = $row['date_added'];
		$date_start = $row['date_start']; ... 

Link to comment
https://forums.phpfreaks.com/topic/146157-solved-randomly-select-3-of-n-records/
Share on other sites

$sql = "SELECT id, date_added, date_start, date_end, title, spaw1, featured FROM $table_name WHERE featured=1 ORDER by rand() LIMIT 3";

$result = mysql_query($sql) or die(mysql_error());

while ($row = mysql_fetch_array($result)) {
         $id = $row['id'];
         $date_added = $row['date_added'];
         $date_start = $row['date_start'];

 

That would work. Mysql has it's own rand() function. Putting that in the order by should randomize the order/results.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.