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 John Tel on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to properly populate an array?

Status
Not open for further replies.

varig77

Technical User
Mar 8, 2006
6
CA
I'd like to know how to populate an array and access its elements anywhere in the script by just using the index of the array. What I am trying to do is to run a database query and populate an array with the results. It works OK if I access the elements within the while statement. However, my goal is to print the array outside of the while statement (something like the script below). Can this be accomplished in PERL? I’ve been using PERL for 2 weeks now so please excuse my lack of knowledge. Thanks to all in advance.

Code:
#!/usr/bin/perl
use DBI;
use CGI::Carp qw(fatalsToBrowser);

print "Content-type:text/html\n\n";

$db_handle = DBI->connect("dbi:mysql:database=DATABASE;user=USERNAME;password=PASSWORD")
    

    $sql = "SELECT * FROM users";
    $statement = $db_handle->prepare($sql)
    $statement->execute()

while (@row = $statement->fetchrow_array) {
}
$db_handle->disconnect();

[b]print  <tr><td>$row[0]</td></tr>;[/b]

[COLOR=red yellow]The following should return all rows of the first column of the table.[/color]
 
Hi, varig77

Following code give a possible solution. Anyway, there should be something better.(I think)
Code:
@result = ();

while (my @row = $statement->fetchrow_array)
{
    push @result , \@row;
}

for (0..$#result)
{
    print   "<tr><td>";
    print join(',' , @{$result[$_]});
    print   "</td></tr>\n";
}
Good Luck.
eewah
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top