• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1759
  • Last Modified:

Help with selectall_hashref

I have this code here, but I'm not shure how can I access the second value from my query in the for loop.

Any help it would be great.

Thank you.
my $ldoc = {}; my $dSQL = "SELECT docID FROM tbl_doc"; 
$sth  = $dbh->prepare($dSQL); 
$sth->execute; $ldoc = $dbh->selectall_hashref($dSQL, 'docID', 'docTitle');
 
foreach $x (keys %$ldoc){
   print "$x\n"; 
}

Open in new window

0
Trexgreen
Asked:
Trexgreen
  • 2
1 Solution
 
mrjoltcolaCommented:
Your query only has one column in the result set.

If you add docTitle to the SELECT, then in your loop you probably just need to acces it via

$ldoc{docTitle}
0
 
mrjoltcolaCommented:
A couple of other things: Since you are using prepare() you don't need to use both execute AND selectall_hashref. selectall_hashref does an execute. You can even have selectall_hashref do the prepare part as well, so all you need is a 1 liner, but if you are going to call the statemnet multiple times you should call prepare first, and then pass $sth to selectall_hashref

Also, I usually use all uppercase in the column names, because Perl hash keys are case sensitive and most databases that I work with return column headers in uppercase.

my $dSQL = "SELECT DOCID, DOCTITLE FROM tbl_doc";
my $sth = $dbh->prepare($dSQL);
my $ldoc = $dbh->selectall_hashref($sth, "DOCID");
 
for my $docID (keys %$ldoc) {
   print "$docID -> $ldoc->{$docID}{DOCTITLE}\n";
}

Open in new window

0
 
TrexgreenAuthor Commented:
Sorry I made a mistake in the last sentence.

it should look like this.

$docID = $dbh->selectall_hashref($dSQL, ['docID', 'docLink']);
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now