You're re-preparing and re-executing your query on each pass through the loop. Is that really what you want to do? Does the value of $order change in the loop?

You should be using placeholders for your variables. Something like:

$sql =<<"SELECT * FROM tbl_admin WHERE day = '$d' AND month = '$m_num' + AND year = '$y' AND expal = '?' AND status= '2'"; if($order == 2 ) { $sql .= " ORDER BY c_name"; } elsif ($order == 3 ) { $sql .= " ORDER BY expal"; } $sth = $dbh->prepare($sql); foreach my $key_expal (keys %expal) { $sth->execute($key_expal) || die $sth->errstr; while ($pointer = $sth->fetchrow_hashref) { my $expalnum = $pointer->{'expal'}; my $comp = $pointer->{'c_name'}; my $cltime = $pointer->{'time'}; my $cltime2 = $pointer->{'time2'}; my $last_name = $pointer->{'last_name'}; my $clnum = $pointer->{'c_number'}; my $status = $pointer->{'status'}; print "<br>L 265 - <b>$comp</b> $expalnum"; } }
Because %expal is a hash, your queries will be run in arbitrary order, but the results of each query should be returned in the order your query specified.

Ordering by expal is redundant, though, when you're specifying that only one expal is acceptable. You might need to rethink your query. Do you really want to use an IN:

$sql = "SELECT * FROM tbl_admin WHERE day = '$d' AND month = '$m_num' +and year = '$y' AND expal IN (".join(',',keys %expal).") AND status= +'2'";
and no outer loop?

The PerlMonk tr/// Advocate

In reply to Re: Foreach Problem! Help!!! by Roy Johnson
in thread Foreach Problem! Help!!! by Anonymous Monk

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.