Forum Moderators: coopster

Message Too Old, No Replies

selecting records randomly?

         

justphp786

9:59 pm on May 6, 2004 (gmt 0)

10+ Year Member



Dear All:

I want to select a record from the table in random fashion.
Like

$myrand=rand(1,25);
select * from faltu where bekar='$myrand';

but here the problems is that rand() returns repeated values. So I used srand() but still the repetition is there. I have 50 records in the table and want to select only 25 of that one at a time. How do I do it.
Thanks.

lildemon

11:30 pm on May 6, 2004 (gmt 0)

10+ Year Member



Try this:

$my_array[] = "0"; //Sets key 0 to value 0

while(!$done)
{
$my_rand = rand(1, 50);
if(!array_search($my_rand, $my_array))
$my_array[]=$my_rand;
if(count($my_array >= 26) $done=TRUE;
}

In theory this should work to provide you an array in which keys 1-25 have all random values for you. The possible problem is for some reason array_search *never* works for me, so you may have to whip up your own version if you have the same problem. The setting of key 0 to 0 is an attempted workaround for the problem.

johnerazo

3:20 am on May 7, 2004 (gmt 0)

10+ Year Member



If array_search() seems to be problematic to you at times, there is another function that does the same, the in_array() function.

$my_array = array();
$lower_bound = 1;
$upper_bound = 50;
$target_size = 25;

for ($i=0;$i<$target_size;$i++) {
$rand_val = rand($lower_bound, $upper_bound);

if (!(in_array($rand_val, $my_array))) {
$my_array[$i] = $rand_val;
}
}

Cheers,
JmErazo

justphp786

6:50 am on May 7, 2004 (gmt 0)

10+ Year Member



Thanks. I have a silly doubt. The code will be executed every time page is open. So across the pages how can we maintain previously created number.

Like, I want to display a record one at time to the user. The record previously displayed should not be reselected. For that I require to generate unique random number across the pages. How do I do it? Will this be done by the code provided? I am unable to grasp it.

Thanks

Cheers

jatar_k

7:23 am on May 7, 2004 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



Welcome to WebmasterWorld justphp786,

what about using sessions/cookies to store the already displayed rows?

If you want to know what they have already seen you are going to need to store it somewhere.

justphp786

8:16 am on May 7, 2004 (gmt 0)

10+ Year Member



Thanks Jatar_k

If you want to know what they have already seen you are going to need to store it somewhere.

this statement is not clear to me. Can you expalin it with more details. Moreover can we store all seen rows as cookie. This as well is not clear to me.

Thanks again and sorry to bother you much.

justphp786

coopster

12:37 pm on May 7, 2004 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



Since http is a stateless protocol, every request is like a brand new request and one way to track what happened in a previous request or requests is to use cookies [php.net].