Jump to content

rand() always returns the same..


w0rtel

Recommended Posts

I want to get a random row from my table. And i use this:

 


$sql = "SELECT * FROM random ORDER BY RAND() LIMIT 1";



$result = mysql_query($sql);

$object = mysql_fetch_object($result);



$rid = $object->rid;

But I always get the first row. Never a different one.. Why?

 

(MySQL v. MySQL 3.23.54-nt)

 

Thnx 4 the help..

Link to comment
https://forums.phpfreaks.com/topic/43-rand-always-returns-the-same/
Share on other sites

I want to get a random row from my table. And i use this:

 


$sql = "SELECT * FROM random ORDER BY RAND() LIMIT 1";



$result = mysql_query($sql);

$object = mysql_fetch_object($result);



$rid = $object->rid;

But I always get the first row. Never a different one.. Why?

 

(MySQL v. MySQL 3.23.54-nt)

 

Thnx 4 the help..

 

Probably because you\'re opening a new connection each time.. The rand() function is not truly random, so you need to give it a near random seed, i.e. use rand(seedvalue)...

 

You may use something like rand(seconds(curdat())) or some other stuff. If you\'re using php you could take a variable and assign a random number to it and them use that as seed in you query.

 

P., denmark

  • 1 month later...

may be u can random selection by doing that:

get the last record from table ( u can do that \"select last_insert_id()\" )

then $min=1 ; $max=$last_record_id ;

$random_record=rand($min,$max);

then u print the random row by mysql_fetch_row..

if u have 10000 records in your table it will search all the records from table then randomize 1 row. searching is too late. but doing like this searching is quite time and it is easy for me :)

see u later

Cihan

  • 2 weeks later...
  • 7 years later...

thanks to the information above I managed to get a good solution:

 

[php:1:d09dd98aa6]<?php

$random_seed=rand(1, time());

$query = \"SELECT * FROM $table ORDER BY RAND($random_seed) limit 1\";

?>[/php:1:d09dd98aa6]

 

Thanks all.

- Dave

 

What if the rand output doesnot equal row value.. It may produce 100 when u have 30 results only...

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.