in reply to Creating a Flexible Database Module

Setup a configuration file that contains all the valid field names for each database stored in hash or lists. This is some code I have been working on that may or may not help you, but has been very useful for my needs.
my %table_fields = ( table1 => [ 'field1' , 'field2' , 'field3' ], table2 => [ 'field1' , 'field2' , 'field3' ], ); sub get_fields { my ($self,$table) = @_; return $table_fields{$table}; }
Now you can pick through your current "keys" and see which ones match valid field names and pass only those to something like:
sub save { my $self = shift; my $table = shift; my $args = shift; # this is your hash of fields and values my @place = (); my @field = (); my @value = (); # # insert into table # foreach (keys %{$args}) { push @place, '?'; push @field, $_; push @value, $args->{$_}; } my $string = qq[ insert into $table ( ] . join(' ,', @field) . qq[ ) values ( ] . join(' ,', @place) . qq[ ) ]; $self->error_to_log("$string"); my $id = $self->db_do($string , \@value ); return ($id); } sub db_do { my $self = shift; my $string = shift; my $placeholders = shift; my $id; $self->error_to_log("$string"); my $cursor = $self->dbh->prepare($string); $cursor->execute(@{ $placeholders }); if ($string =~ /^\s?insert/i) { $id = $self->dbh->{'mysql_insertid'}; $self->error_to_log("ID $id",1); } return ( $id ); }

Replies are listed 'Best First'.
Re: Re: Creating a Flexible Database Module
by gwhite (Friar) on Jan 28, 2002 at 22:47 UTC

    That looks like it is on the right track, I will probably adjust it to:

    my %table_fields = ( table1 => [ 'field1||objectname1' , 'field2||objectname2' , 'fiel +d3||objectname3' ], table2 => [ 'field1||objectname1' , 'field2||objectname8' , 'fie +ld3||objectname10' ], );

    Then I can split each element and have the user object that the data lives in right handy also. Good one, thanks

    g_White