Nik has asked for the wisdom of the Perl Monks concerning the following question:

$st = $db->prepare( "SELECT count(*) FROM members WHERE user=?" ); $st->execute($user); $rows = $st->fetchrow_array(); if ($rows) { print font( {-size=>5, -color=>'Lime'}, "Το όνομα Χρήστη είναι π +ιασμένο! Παρακαλώ διάλεξε ένα άλλο!" ); exit 0; }
i try the above to check if there are any records returned but it fails. any idea why?
and also
$st = $db->prepare( "SELECT count(*) FROM members" ); $st->execute(); $row = $st->fetchrow_hashref; print $row->{'count(*)}
i am trying the above to get the total number of rows returned from the sql statement but it aint working why?

Replies are listed 'Best First'.
Re: fetching rows problem
by b10m (Vicar) on Feb 25, 2004 at 21:32 UTC

    The first piece of code seems "valid" to me. Could you specify what exactly fails?

    As for the second snippet, you have a typo in there (print $row->{'count(*)} you forget an apostrophe (') ). I would write it something like this (to make it more readable):

    $st = $db->prepare("SELECT count(*) AS total FROM members"); $st->execute(); my $row = $st->fetchrow_hashref(); print $row->{total}."\n";

    Update: You can use your approach, but don't forget the apostrophe (single quote):

    print $row->{'count(*)'}."\n";
    --
    b10m

    All code is usually tested, but rarely trusted.
Re: fetching rows problem
by matija (Priest) on Feb 25, 2004 at 21:24 UTC
    Instead of $rows = $st->fetchrow_array();

    You should do ($rows) = $st->fetchrow_array();

    The reason for this is that you want the first element of the returned array in your $row - if you do it without the parens, you will get the number of elements in the array, which is not what you want.

    For your second problem, change your SQL to SELECT count(*) as c FROM members. Once you've done that, you can reference the value as  $$row{c}.

      if you do it without the parens, you will get the number of elements in the array,

      No. It doesn't work that way.

      fetchrow_array in scalar context will return the first or the last field (See DBI specification change). Which one is currently undefined, but with a query that returns only one value the issue is irrelevant.