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

CGI/DBI no results marker

I'm running a CGI script that uses Perl DBI to check for records in an access database.  I'd like the users to get a message if their search doesn't have any matches, but I can't find a way to get it to work.  The criteria are entered via html form, then used to build a SQL statement that searches through the ODBC to the access DB.  Pretty simple stuff -- the problem is that I have a

while (@row=$sth->fetchrow_array)

statement in there for getting results.  I tried running comparisons on the contents of @row, but since no results in the DB causes a failure in the while loop, that's no good.  I've tried putting the assignment into an if statement, but then if it succeeds, I lose the first match from the search.

All I want is a way to check whether the SQL statement got any results from the database, and display a quick note if not.  I'm thinking there's got to be a simple way to do it, but I haven't stumbled my way into it yet.
1 Solution
You could use a flag for this:

$no_hits = 1;

while(@row = $sth->fetchrow_array) {
   $no_hits = 0;

if($no_hits) {
  print "Search returned no results";

Or something like that.
I have not tested this but I think it should do what you need.

$rows = $sth->fetchall_arrayref();

if ($rows) {
    foreach my $row (@$rows) {
        #  process each row
else {
    print "No search results";

Featured Post

Become an Android App Developer

Ready to kick start your career in 2018? Learn how to build an Android app in January’s Course of the Month and open the door to new opportunities.

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