in reply to Single mysql query

You don't have to fetch all the rows.

$sth->execute($id); my $row = $sth->fetch(); $sth->finish(); if ($row) { ... } else { # No more images ... }

The selectrow_* methods are convenient shortcuts when you expect at most one row. Any extra rows returned by the query are ignored.

my $row = selectrow_arrayref($stmt_or_sth, undef, $id); if ($row) { ... } else { # No more images ... }

Note: I assumed RaiseError was true.