Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks!
I am fetching a database but I want to use a "WHILE" loop instead of a "FOR" loop, how could I do this here, here is a sample code to demonstrate what I am trying to do:
my $sql = "select name,address,phone,email from my table where name='m +ary'"; my $allnames= $dbh->exec_select( $sql ) or die "Couldn't execute state +ment: $dbh->errstr";; if(@$allnames) { for (my $i = 0; $i < @$allnames; $i++) { my $allname = $allnames->[$i]{ 'name' } || ''; my $alladdress = $allnames->[$i]{ 'address' } || ''; my $allphone= $allnames->[$i]{ 'phone' } || ''; my $allemail = $allnames->[$i]{ 'email' } || ''; $AoH{ alldata } = $allname."&nbsp;".$alladdress."&nbsp;".$all +phone ."&nbsp;".$allemail; }


Thanks!

Replies are listed 'Best First'.
Re: Fetching DB using a While loop.
by almut (Canon) on Apr 20, 2010 at 18:30 UTC
    I want to use a "WHILE" loop instead of a "FOR" loop
    my $i = 0; while ($i < @$allnames) { .... $i++; }

    instead of

    for (my $i = 0; $i < @$allnames; $i++) { .... }

    But why...?  — Maybe you rather want something like

    for my $elem (@$allnames) { my $allname = $elem->{name} || ''; my $alladdress = $elem->{address} || ''; ... }
Re: Fetching DB using a While loop.
by leighsharpe (Monk) on Apr 21, 2010 at 00:33 UTC
    my $sql = "select name,address,phone,email from my table where name='m +ary'"; my $sth=$dbh->prepare($sql) or die "Couldn't prepare statement handle: + ".$dbh->errstr(); my $count=$sth->execute() or die "Couldn't execute statement:".$dbh->e +rrstr(); while (my @row=$sth->fetchrow_array()) { $AoH{ alldata } = join ('&nbsp;', @row); } $sth->finish();
    But what is 'alldata'? The row inside the loop will continually overwrite its own results, I suspect you actually want something more like:
    push(@some_array, join('&nbsp;', @row));
    Oh, and of course, you'll be using placeholders in the real thing, right?
    my $sql="select name,address,phone,email from my table where name=?"; my $sth=$dbh->prepare($sql) or die "Couldn't prepare statement handle: + ".$dbh->errstr(); my $count=$sth->execute('mary') or die "Couldn't execute statement:".$ +dbh->errstr();