PDA

View Full Version : Loop - if/else not working properly :confused:


bazz
09-08-2008, 05:55 PM
Hi,

This really shouldn't be happenin' to me.

Having queried the db for existing room numbers and then, using the form input, I want to insert the numbers which are not already in the db. it will only run one side of the if/else conditional.


foreach my $new_room_number (sort @room_numbers)
{
$select_room_number->execute($business_id, $new_room_number);

while (my @room_numbers = $select_room_number->fetchrow_array)
{
#print qq( @room_numbers ... ); outputs ok
#push(@stored_room_numbers,@room_numbers);

if ($new_room_number == $room_numbers[0])
{
print qq( duplicate $new_room_number <br />); # outputs OK
} else {
print qq(
ndn= $new_room_number <br />
inserted $new_room_number <br />
); # not happening
$insert_into_tbl->execute($business_id, $new_room_number); # not happening either
}
}
}



even if I use 'unless' to force the second half of the if/else, to run, it only runs when the numbers exist so I can;t input new numbers. :(

what am I missing.

bazz

FishMonger
09-08-2008, 07:28 PM
Drop the outer foreach loop and put the room numbers into a %room_numbers hash instead of the @room_numbers array.

Then, in the while loop you check for the existence of the hash key.

if ( exists $room_numbers{$room_numbers[0]} )

bazz
09-11-2008, 04:55 PM
Thank you FishMonger you got me back on track. :thumbsup:

I am having to do it the 'other way around'. I need to loop through the proposed new room numbers and check if they are in the hash, which is built from a db query. It seems to work but, would anyone please confirm that I am building the hash (highlighted), correctly.



while (my @queried_room_numbers = $select_room_number->fetchrow_array)
{
$existing_room_numbers{$queried_room_numbers[0]} = $queried_room_numbers[0];
}


It seems strange using the same var twice but I don't recall another way.

bazz

FishMonger
09-11-2008, 05:26 PM
It depends...do you want/need to have both the key and value equal to the room number?

I'd think that since it will be used/queried in boolean context, the value could simple be 1.
while (my ($room_number) = $select_room_number->fetchrow_array) {
$existing_room_numbers{$room_number}++;
}