in reply to Database Output

You want to call fetchrow_hashref once.   When you’ve done this, $rec now contains a hashref containing the entire row:   all of the columns mentioned in your SELECT statement are simultaneously present in it.   Each time you call it, another row is fetched, until no more rows exist, whereupon it returns undef.

Another thought (caution: extemporaneous coding-sketch, stripped to the bone...)

# PREPARE THE STATEMENT ONCE; USE PLACEHOLDERS my $sth = .. prepare('select ... where field3=? ...'; foreach my $cookie_name (qw/C1 C2/) { # LIST OF NAMES my $cookie_value = $cgi->cookie($cookie_name); if (defined($cookie_value)) { # FOUND A COOKIE! $sth->execute(($cookie_value)); # BIND PARAMETERS ON-THE-FLY if (my $rec = $sth->fetchrow_hashref ...

The essential ideas here are:

  1. The query is prepared only one time.   Placeholders (un-quoted ? marks) are used to allow specific values to be bound to them.
  2. An arrayref is used in the execute call to provide values on-the-fly (left to right).   Not surprisingly (this is Perl, after all...) this is not the only way to do it...
  3. A list of cookie-names is used to avoid writing repetitive code.
  4. The cookie-value is always grabbed into a variable.   Then, the defined() function is used to check for the cookie’s existence, instead of a test for “a True value.”
  5. (It is safe to use if (my $rec ... fetchrow_hashref ... as-written, because we know that this method will either return a hashref or undef.)