Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Perl, MySQL, fetcharray, while

Status
Not open for further replies.

jollyroger

Technical User
Mar 22, 2001
77
GB
Hello there
Please can somebody help us? We are trying to create a web page after querying a mysql database.
We have managed to connect to the database and we get results from it, we have also managed to print this results onto a web page using:
while ( @ary=sel1->fetcharray() ) {
print &quot;The query results: $ary[0] and $ary[1]&quot;,&quot;<br>\n&quot;;
}
BUT we don't want to do this. We want to capture the array in the bit here and then use it somewhere else in the script!
For example:
@ary=sel1->fetcharray();
But when we do this we get nothing back, even though earlier in the script we have called the array using the above print command?
Also, we have got an error message telling us that there is a unatural database disconnect.
Finally just for your information the database query is contained within a sub routine which is called earlier on in the script.
Any idea's
Thanks
Jollyroger

 
The 'fetcharray' method returns one db record at a time as an array of fields. So, one iteration of

@array = $sth->fetcharray()

gets just one record. In order to get all the incoming records, just push them onto another array.


To illustrate, the incoming record is joined to make a string and then each string is pushed onto the records array.
Code:
while (@fields = $sth->fetcharray()) {
my $tmp = join '|', @fields;
push @records, $tmp;
undef $tmp;
}
# print pipe separated output of each record.
foreach (@records) { print &quot;$_\n&quot;; }

While that serves to illustrate getting your records, you probably would not want to do it quite that way. Maybe something more like.....
Code:
my $sth = $dbh->prepare(&quot;select * from table&quot;);
$sth->execute();
while (my @row = $sth->fetchrow){ push @sequence, \@row; }
$sth->finish();

foreach $rec (@sequence) {
    print &quot;${$rec}[0], ${$rec}[1]\n&quot;; 
    }

Even better, get a copy of &quot;Programming the Perl DBI&quot; by Descartes and Bunce from O'Reilly for a good, practical, and concise treatment of using fetchrow, fetchrow_array, fetchrow_arrayref, and fetchrow_hashref.

'hope this helps

If you are new to Tek-Tips, please use descriptive titles, check the FAQs, and beware the evil typo.
 
Thanks for this, I have tried this and it works a treat!!!!

With regards

Jollyroger
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top