rsiedl has asked for the wisdom of the Perl Monks concerning the following question:
#!/usr/bin/perl # Modules used use strict; use warnings; use DBI; # Database Definition our $dbh = &DB_OPEN('db_name','localhost','3306','db_user','db_passwor +d'); sub DB_OPEN { my ($db_name,$host_name,$port,$db_user,$db_pass,) = @_; my $database = "DBI:mysql:$db_name:$host_name:$port"; my $dbh = DBI->connect($database,$db_user,$db_pass); } # Retreive Database data sub DB_GET { my ($table,$refkey,$refval) = @_; my (%db_data,$sth); my $select = "select "; $sth = $dbh->prepare("desc " . $table); $sth->execute; while ( my ( $NAME, $TYPE, $NULL, $KEY, $DEFAULT, $EXTRA ) = $sth->f +etchrow ) { $select .= "'$NAME',$NAME,"; } # end-while $sth->finish; chop($select); $select .= " from $table"; if ($refval) { $select .= " where $refkey=?"; } $sth = $dbh->prepare( $select ); if ($refval) { $sth->execute($refval); } else { $sth->execute(); } while ( my ( @array ) = $sth->fetchrow_array ) { my %tmp_hash; my $ref = $array[1]; for (my$i=0;$i<scalar(@array);$i+=2) { if ($array[$i] eq "$refkey") { $ref = "$array[$i+1]" } $tmp_hash{$array[$i]} = $array[$i+1]; } # end-for $db_data{$ref} = { %tmp_hash }; } # end-while $sth->finish; %db_data; }
my %db_data = &DB_GET('clients', 'client_id', $client_id);
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: easier to get data from a database
by Joost (Canon) on Jul 12, 2005 at 16:44 UTC | |
|
Re: easier to get data from a database
by fmerges (Chaplain) on Jul 12, 2005 at 16:45 UTC | |
|
Re: easier to get data from a database
by kirbyk (Friar) on Jul 12, 2005 at 16:47 UTC | |
|
Re: easier to get data from a database
by davidrw (Prior) on Jul 12, 2005 at 16:53 UTC | |
|
Re: easier to get data from a database
by Tanktalus (Canon) on Jul 12, 2005 at 19:57 UTC |