Using Perl and MySql, how can I check for an empty result?

Simplified simplification example:

# Get Some data $query = $db->prepare(qq{ select * from my_table where id = "Some Value" }); $query->execute; # Iterate through the results if ( *THE QUERY HAS RETURNED A RESULT* ) { print "Here is list of IDs "; while ($query_data = $query->fetchrow_hashref) { print "$query_data->{id}"; } }; 

We are looking for a code for "QUESTION RETURN RESULT". I would like to avoid using count (*) in my SQL, if possible, as this will require "group by".

+4
source share
3 answers
 my $sth = $dbh->prepare($stmt); $sth->execute(); my $header = 0; while (my $row = $sth->fetchrow_hashref) { print "Here is list of IDs:\n" if !$header++; print "$row->{id}\n"; } 

Alternative:

 my $sth = $dbh->prepare($stmt); $sth->execute(); my $row = $sth->fetchrow_hashref; print "Here is list of IDs:\n" if $row; while ($row) { print "$row->{id}\n"; $row = $sth->fetchrow_hashref; } 

Simplified code due to memory:

 my $ids = $dbh->selectcol_arrayref($stmt); if (@$ids) { print "Here is list of IDs:\n"; print "$_\n" for @$ids; } 
+6
source

It looks like your check for the query result is superfluous. Your while loop will evaluate to false if there is no line to retrieve.

+1
source

old / wrong answer

If you use DBI with DBD::mysql , then $query->rows; will return you the number of lines selected (or affected in the record statement) by your expression.

EDIT

Please do not use this and take a look at the comment on this answer @Luke The Obscure

0
source

All Articles