Molten Monks,

Why is my code assigning the last-retrieved value to all elements in my hash?

I have a DB table, "booklist_table" that holds information about books to be published. As the book evolves, it can change title, and each time it does a new entry is made in the table with a unique update_id. The object of this script is to pull out all the LATEST titles of all books in the table and tell me the update_id's of those records. We start with a hash of book IDs, %booklist_1, where the keys are the IDs.

$sql = "select update_id, title from booklist_table where (book_id = ? +) order by update_id desc limit 1"; $sth = $dbh->prepare($sql) or die("Could not prepare!" . $dbh->errstr) +; foreach $book_id (keys %booklist_1) { $sth->execute($book_id) or die("Could not execute!" . $dbh->errstr +); ($update_id, $title) = $sth->fetchrow_array(); $booklist_1{$book_id}{'update_id'} = $update_id; $booklist_1{$book_id}{'title'} = $title; print "$book_id > $booklist_1{$book_id}{'update_id'}\n"; } $sth->finish; foreach $book_id (keys %booklist_1) { print "XXX $book_id > $booklist_1{$book_id}{'update_id'}\n"; }
The second loop is a temporary debugging tool to see how the booklist_1 hash was populated. The script gives me this output:
100 > 456 101 > 753 102 > 489 103 > 259 XXX 100 > 259 XXX 101 > 259 XXX 102 > 259 XXX 103 > 259
That is, every $booklist_1{$book_id}{'update_id'} is being set to the last retrieved update_id.

What the heck?

Thanks.




Time flies like an arrow. Fruit flies like a banana.

In reply to Why is my code assigning the last-retrieved value to all elements in my hash? by punch_card_don

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.