0

I have seen many articles on this, and none are working for me. I have this code -

$var1->{reference} = sql_get_rows();   


sub sql_get_rows(){
    etc
    return ($sth->fetchall_arrayref());
 };

What I want to do is know how many rows are found in the SQL statement and stored in $var1->{reference} (or be told a better way to approach the problems. I have written what $var1->{reference} is storing below.

warn Dumper ($var1->{reference});

'$VAR1 = [
      [
        26412502,
        'initial'
      ],
      [
        49246682,
        'title'
      ],

Note that I know how to find the COUNT by an SQL statement, thats not what I want to know.

Thanks

justintime
  • 3,601
  • 4
  • 22
  • 37
Geo1986
  • 65
  • 1
  • 2
  • 8

1 Answers1

2

If using DBI, use the rows method

my $sth = $dbh->prepare(q{...});
$sth->execute(@bound_variables) or die $dbh->errstr;

print "Rows = " . $sth->rows;

As @ThisSuitIsBlackNot pointed out, this may not work, so if you're pulling all of the records, just count the data structure:

print "Rows = " . scalar @{$var1->{reference}};
Miller
  • 34,962
  • 4
  • 39
  • 60
  • From the very docs you linked to: "Generally, you can only rely on a row count after a non-`SELECT` execute (for some specific operations like `UPDATE` and `DELETE`), or after fetching all the rows of a `SELECT` statement. For `SELECT` statements, it is generally not possible to know how many rows will be returned except by fetching them all. Some drivers will return the number of rows the application has fetched so far, but others may return -1 until all rows have been fetched. *So use of the `rows` method or `$DBI::rows` with `SELECT` statements is not recommended.*" (emphasis added) – ThisSuitIsBlackNot Mar 12 '14 at 22:16
  • Since the OP already has an arrayref with the results of the query, why not just `my $rows = @$arrayref`? – ThisSuitIsBlackNot Mar 12 '14 at 22:21
  • @ThisSuitIsBlackNot Yes, I typically use it to check for existance of rows rather an worry about an exact count. IE `if (! $sth->rows)`. I've added the obvious, just count the data structure to the answer though. – Miller Mar 12 '14 at 22:27