Hi Monks

I've just written a little snippet to allow me to retrieve data from a mysql database without all the usual DBI prepare, execute, fetchrow every time i need to access the db.

I was just after your thoughts and criticism's.

Here it is...
#!/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; }

Then I just include the above file and I can use it with something like:
my %db_data = &DB_GET('clients', 'client_id', $client_id);

Thanks
Reagen

In reply to easier to get data from a database by rsiedl

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.