Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic

Re: Weird DBI/Array Use

by madhatter (Sexton)
on Jan 08, 2001 at 03:29 UTC ( #50413=note: print w/replies, xml ) Need Help??

in reply to Weird DBI/Array Use

If I know that my query is going to return only one entry, how do I avoid using a loop to gather the returned data? Anything I try just returns me an array reference.
my $result = db_execute($SQL); foreach(@$result){ my ($title,$body) = @$_; print $title; }

Replies are listed 'Best First'.
Re: Re: Weird DBI/Array Use
by Fastolfe (Vicar) on Jan 08, 2001 at 03:48 UTC
    If you have an array reference that you "know" will only contain one item, then it sounds like you just want to access the first element of the array:
    my $result = db_execute($SQL)->[0]; my ($title, $body) = @{$result}; # or my ($title, $body) = @{db_execute($SQL)->[0]};
    Check out perlref, perllol and especially perldsc for information about references and the ways you can use them.
Re: Re: Weird DBI/Array Use
by repson (Chaplain) on Jan 08, 2001 at 08:21 UTC
    If you only want one row then do use
    my @result = $dbh->selectrow_array("SELECT MAX(foo) FROM blah");

    If you just want one column then
    my @rows = @{ $dbh->selectcol_arrayref("SELECT id FROM blah") };

    Otherwise do a full $dbh->selectall_arrayref as salvadors suggests or use the full prepare, execute, fetchrow syntaxes like you were doing originally.

    For information on these syntaxes and more read up on the DBI docs.

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://50413]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (1)
As of 2022-01-19 04:22 GMT
Find Nodes?
    Voting Booth?
    In 2022, my preferred method to securely store passwords is:

    Results (55 votes). Check out past polls.