List:General Discussion« Previous MessageNext Message »
From:Paul DuBois Date:November 7 2000 3:08pm
Subject:Re: Read field names after select *
View as plain text  
At 8:22 PM +0000 11/6/00, Mark Worsdall wrote:
>I am trying to get the names of fields from my database, so looking
>through previous postings I found to use fetchrow_hashref
>my $dbh = DBI->connect( "dbi:$datasrc", "$sqlUser", "$sqlPassword") or
>die DBI->errstr;
>my $sth = $dbh->prepare("SELECT * FROM $sqlTable");
>my $hashref = $sth->fetchrow_hashref;
>foreach ( %hashref ) {
>         print "At column $_ we have value $hashref{$_}\n";
>$dbh->disconnect or die DBI->errstr;
>But, I am stumped now cos I get this error:-
>Global symbol "%hashref" requires explicit package name at ./
>line 22.
>Global symbol "%hashref" requires explicit package name at ./
>line 23.
>Execution of ./ aborted due to compilation errors.

$hashref is a reference, not a hash.  You can't use it as "%hashref".
Use it as %{$hashref}.

If you want to know the names of the fields, then you can use either
keys(%{$hashref}) or (perhaps simpler for you) $sth->{NAME}, which
is a reference to an array of the column names in your query.  Use it
like this:

	foreach my $col_name (@{$sth->{NAME}}) ...

Note, if you use $sth->{NAME}, you should do so right after your
execute() call.  The values in the array don't last past finish().
You can grab the values if you want to save them for later like this:

my @col_names = @{$sth->{NAME}};

Paul DuBois, paul@stripped
Two MySQL connections with PHP?Jordi AmorĂ³s6 Nov
  • Re: [PHP] Two MySQL connections with PHP?Rasmus Lerdorf6 Nov
  • Read field names after select *Mark Worsdall6 Nov
    • Re: Read field names after select *Paul DuBois7 Nov