Seconds calculation problem - insert in mysql

Hi

I have the following problem:

$rand_start = rand(2, 8);
$rand_misc = rand(2, ($SECS_DURATION - 5));
$rand_end = rand(($SECS_DURATION - 11), ($SECS_DURATION - 4));

variables $rand_start, $rand_misc, $rand_end are inserted in mysql table.
most of the time, values like 6,8,12 is inserted which is what I want, but sometimes values like 346261932 are inserted in rand_misc and rand_end fields. It never happen with rand_start field.

Fields in the database are int(11)

$SECS_DURATION variable should be time in seconds, but I don’t know how to declare it to be so.

Inserting values like 346261932 in my table, cause my script to halt and to stop to work.

Anyone can help me to ensure that I will always insert values in seconds (1-59) in my table? What should I do with $SECS_DURATION variable so I can ensure that time in seconds will be inserted in my table?

Regards, zoreli

You need to see what the value of $SECS_DURATION is when the script is going wrong. What range of values would you expect for $SECS_DURATION? Perhaps filter it before you rand() lines with something like:

$SECS_DURATION = min($SECS_DURATION, 59);
$SECS_DURATION = max($SECS_DURATION, 12);

The reason the lower limit is 12, is because your code subtracts 11 for the min in $rand_end, but you say you want values from 1,59.

Are the fields in your db set to unsigned or not?

I’m confused by what you’re trying to do here.
You want… a random value between 1 and 59? rand(1,59).

[fphp]mt_rand[/fphp](1, 59)

(On most servers mt_rand runs slightly faster than rand and is more consistently random (whatever that means))

If I could just ensure that $SECS_DURATION has format of seconds I will be fine. This value is entered by user, and it may be 90,60,45…or some other value. So I need to ensure that result from the calculation

$rand_misc = rand(2, ($SECS_DURATION - 5));
$rand_end = rand(($SECS_DURATION - 11), ($SECS_DURATION - 4));

will be seconds, that is simple integer, and not value like: 346261932 I will be fine.

Hope that this will clarify my goal. Thanks to all of you for your replies.

Regards, Zoreli

if(!is_int($SECS_DURATION)) { $SECS_DURATION = 0; }
$SECS_DURATION %= 60

Aha… Yeah, trying to insert a negative number into an unsigned field will roll over to the the highest possible number. So you must make sure the second number cannot be lower than the higher.

Let’s look at your code


$rand_start = rand(2, 8); 
$rand_misc = rand(2, ($SECS_DURATION - 5)); 
$rand_end = rand(($SECS_DURATION - 11), ($SECS_DURATION - 4)); 

So, if $SECS_DURATION is 4 or less, negative numbers will be in the range.

I think you are going about this all wrong. If you know what the duration is then all is left is to randomly choose a start time - the end time will be a fixed interval after the start. If the duration is variable, store that.