1

Is there a way to check if a DBI->execute statement returns an empty set? The purpose is that I want to create a table, and then ask for username, if the username isn't in the table, (check for empty fetch() statement), then add to table. Any suggestions?

    $sth = $dbh->prepare("SELECT * FROM table_name_here");
    $sth->execute();

    if(...$sth->fetch() was empty...)
    do something...

4 Answers 4

2

Try that :

$sth = $dbh->prepare("SELECT * FROM table_name_here");
$sth->execute();

unless ($sth->fetch()) { do something..; }
Sign up to request clarification or add additional context in comments.

Comments

2

Is there a way to check if a DBI->execute statement returns an empty set

Yes.

$sth = $dbh->prepare("SELECT * FROM table_name_here");
$sth->execute();
unless( $sth->rows ) {
    #empty set
}

1 Comment

This doesn't work for SELECT statements. From the documentation of the 'DBI' module: "For 'SELECT' statements, it is generally not possible to know how many rows will be returned except by fetching them all"
2

I suggest you do a preliminary fetch of the number of records, like this

my ($records) = $dbh->selectrow_array('SELECT count(*) FROM table_name_here');

2 Comments

will this tell me how many different entries that will return? So if I had 4 entries in a table, this would set $records = 4?
It will tell you how many records are in the table, whether or not they are different (although you will more than likely have at least one unique column, in which case they must all be different). I suggest you experiment. Bear in mind that there is a very slim chance that the number of records changes between you fetching the count and fetching the data itself.
1

One possible approach to do that:

my $row_count = 0;
while (my @ary = $sth->fetchrow_array() ) { ...; $row_count++; }
unless ($row_count) { 
  ...
}

But I can't help wondering why do you need to use fetchrow, and not fetchall, for this specific case. In fact, I'd reorganize it this way:

my ($count) = $dbh->selectrow_array('
   SELECT COUNT(*) FROM users WHERE username = ?'
   undef, $username);
if ($count) { ... } 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.