in reply to Perl-MySQL get column names

Another technique for dealing with "relat(ing) a value to it's column name" is to use
$sth->fetchrow_hashref
This returns an anonymous hash for each row, with the column names as keys. I use this a lot (hashes are the best data type for most things in Perl, anyways). Normally it's bad to
SELECT *
There are obvious performance reasons for retreiving only the data you need, but if you're usually needing most of the columns in a row, then the difference is often slight. The real reason not to SELECT * is that when you use $sth->fetchrow_array or any other such methods that retrieve the row as a list, then if you change the table schema, you might get your data back in the row order. With none of your code having been changed! But if you use $sth->fetchrow_hashref (or $sth->fetchall_hashref, etc) then this isn't a problem, because the keys in the hash are the column names. So not only you can safely SELECT *, but then when you do, and your table schema has changed, you don't have to modify your SQL. You can either just ignore the new columns, or if you need them, there they are in your hashes. Poof!

I like this approach, because when I make changes it Does What I Mean.


--
Snazzy tagline here

Replies are listed 'Best First'.
Re^2: Perl-MySQL get column names
by kiat (Vicar) on Nov 08, 2004 at 06:29 UTC
    Thanks, Aighearach!

    $sth->fetchrow_hashref
    doesn't seem to work because of UNION. I've tried it out but I don't seem to be able to get to the column names - I got choice1 as the column.