Jump to content

Archived

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

w0rtel

rand() always returns the same..

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..

Share this post


Link to post
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

Share this post


Link to post
Share on other sites

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

Share this post


Link to post
Share on other sites

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

Share this post


Link to post
Share on other sites

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...

Share this post


Link to post
Share on other sites

Google "mysql why order by rand is bad".

Share this post


Link to post
Share on other sites

Google "mysql why order by rand is bad".

Or read the stickies.

Share this post


Link to post
Share on other sites

×

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.