Reputation: 87
I need to store the fetched data from the MySQL database. So I used this code.
while (@row = $statement->fetchrow_array)
{
print "@row.\n"; # ------printing data
}
foreach $key(@row)
{
print $key."\n"; # ------empty data
}
In foreach loop the @row data is empty. How to solve this
UPDATE: It actually should be like this:
while (my @row = $statement->fetchrow_array) {
# print "@row.\n";
foreach my $key(@row) {
$query= "ALTER TABLE tablename DROP FOREIGN KEY $key;";
$statement = $connection->prepare($query);
$statement->execute()
or die "SQL Error: $DBI::errstr\n";
}
}
Upvotes: 0
Views: 688
Reputation: 106375
Well, it should be like this:
while (my @row = $statement->fetchrow_array) {
foreach my $key (@row) {
print $key."\n";
}
}
Otherwise all the result set will be consumed in the first loop.
As a sidenote, fetchrow_array
returns a rowset as array of field values, not keys. To get the keys as well, you should use fetchrow_hashref
:
while (my $row = $statement->fetchrow_hashref) {
while (my ($key, $value) = each %$row) {
print "$key => $value\n";
}
}
UPDATE: from your comments it looks like you actually need an array of column names. There's one way to do it:
my $row = $statement->fetchrow_hashref;
$statement->finish;
foreach my $key (keys %$row) {
# ... dropping $key from db as in your original example
}
But in fact, there are more convenient ways of doing what you want to do. First, there's a single method for preparing and extracting a single row: selectrow_hashref
. Second, if you want to get just foreign keys information, why don't use the specific DBI method for that - foreign_key_info
? For example:
my $sth = $dbh->foreign_key_info( undef, undef, undef,
undef, undef, $table_name);
my $rows = $sth->fetchall_hashref;
while (my ($k, $v) = each %$rows) {
# process $k/$v
}
Upvotes: 1