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

$a = find_items("26"); print "$a"; sub find_items { $idd = shift; $sth3 = $dbh->prepare("SELECT category FROM items WHERE category = '$ +idd'"); $sth3->execute or die $dbh->errstr; $rvf = $sth3->rows; $a += $rvf; $sth23 = $dbh->prepare("SELECT id FROM category WHERE parent = '$idd' +"); $sth23->execute or die $dbh->errstr; while ($idg = $sth23->fetchrow_array) { $item = find_items($idg); $a += $item; } return($a); }
This is suppost to be printing 25 not 124

Replies are listed 'Best First'.
Re: Printing wrong results
by cfreak (Chaplain) on Jul 26, 2002 at 19:35 UTC

    Well there are several things you can do. Number one being

    'use strict' and
    'use warnings'

    also declare your variables with 'my' especially in the sub-routine, they are all global at the moment. Also it doesn't make much diffence in Perl but you are passing your integer (26) as a string, you should probably remove the "" characters.

    Some other problems

    You have a recursive call to find_items() which is normally not a good idea.

    You have multiple statement handles($sth3,$sth23), its usually better to have one statement handle and call finish() on it after each statement is completed.

    Those things will probably go a long way toward finding your problem.

    As for you immediate problem its kind of hard to tell without knowing what you are trying to do or what is in your database. But my guess would be that you are getting unexpected results because '$a' is global and gets added to through every recusive call to find_items()

    Hope that helps
    Chris

    Lobster Aliens Are attacking the world!
Re: Printing wrong results
by Anonymous Monk on Jul 26, 2002 at 19:23 UTC
    sub find_items { $idd = shift; $sth23 = $dbh->prepare("SELECT id FROM category WHERE parent = '$idd' +"); $sth23->execute or die $dbh->errstr; while ($idg = $sth23->fetchrow_array) { $itemn = find_items($idg); my $adf += $itemn; } $sth3 = $dbh->prepare("SELECT category FROM items WHERE category = '$ +idd'"); $sth3->execute or die $dbh->errstr; my $rvf = $sth3->rows; my $bdf += $rvf; $cdf = $adf + $bdf; return($cdf); }
    Can someone please tell me why that worked
      Actually it didnt work