sub add_customer { # $data_hash is a hashref representing the fields # in the customers table that will be filled. my ( $data_hash ) = @_; my ( $fields, $values, $place_holders ) = format_insert_data( $data_hash ); my $sth = $dbh->prepare( "INSERT into customers ( $fields ) VALUES ( $place_holders )" ); $sth->execute( @$values ); } sub format_insert_data { # Takes a hash ref with keys being field names and # values being the values to insert into the database and # returns a list of fields, values, and placeholders suitable for an SQL INSERT statement: # INSERT into table ( $fields ) VALUES ( $place_holders ) my ( $hash_ref ) = @_; if ( ref $hash_ref ne 'HASH' ) { croak "Argument to format_insert_data must be a hash reference"; } my @fields = keys %$hash_ref; my $fields = join ',', @fields; my @values = @$hash_ref{ @fields }; my $place_holders = '?,' x scalar @fields; chop $place_holders; # remove trailing comma return ( $fields, \@values, $place_holders ); }