inblosam has asked for the wisdom of the Perl Monks concerning the following question:
And here is the script making the object, etc.:package User; use strict; use DBI(); use Data::Dumper; sub new { my $class = shift; # Connect to the database. my $dbh = DBI->connect("DBI:mysql:database=somedb;host=localhost","use +rname", "password",{'RaiseError' => 1}); # Now retrieve data from the table. my $sth = $dbh->prepare("SELECT username,email,phone FROM users"); $sth->execute(); ### gets the columns from the query my @columns = @{$sth->{'NAME'}}; ### this maps the columns to their order in a hash ### so later with the value of the column key I can look it up ### from the final array my %columns = map { $columns[$_] => $_ } (0..$#columns); ### this grabs all the data from the query, with the array ### having the fields in the same order as numbered in the %columns my $self = $sth->fetchall_arrayref(); ### this works here when uncommented # print "$columns{email}\n"; ### this works and shows the column to number mapping print Dumper(\%columns); ### same as below except ", 'User'" is added to end print Dumper(\$self); return bless $self, $class; } ### gets the data from the database sub get_user { my $self = shift; my $row = shift; my $field = shift; ### just prints out the contents of $self variable print Dumper(\$self); ### In comments is what I want to do, call in the row and the field ### and get the proper data back, like... # return $self->[$row][$column{$field}]; ### but I can't seem to get the %column data in this subroutine. ### when I run it I get: Global symbol "%column" requires explicit p +ackage name at User.pm line 39. ### but this is all I can get to work right now. return $self->[0][1]; } 1;
The problem is in the User.pm I can't seem to figure out how to call the %columns hash in the subroutine. There may be other problems, but this one I haven't been able to figure out yet. Any help would much appreciated!#!/usr/bin/perl -w use strict; use User; ### create a new object my $user = User->new(); ### call some data, $object->sub(row,'field') print STDOUT "User ID is:", $user->get_user(0,'username'), "\n"; exit 0;
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Database hash/array mapping and OO
by Aragorn (Curate) on May 15, 2004 at 14:23 UTC | |
|
Re: Database hash/array mapping and OO
by Fletch (Bishop) on May 15, 2004 at 13:47 UTC | |
by inblosam (Monk) on May 15, 2004 at 13:58 UTC | |
by Fletch (Bishop) on May 15, 2004 at 15:23 UTC |