How can this method that inserts a hashref into a database table be improved? It assumes that the columns of the database table are named identically to the fields in the hashref. The return value is the id field created by the insert.
sub insert(){
my ($table, $data) = @_;
my ($fields, $placeholders, $values) = ("", "", []);
while (my ($field, $value) = each %$data){
$fields.=", " if ($fields);
$fields.=$field;
$placeholders.=", " if ($placeholders);
$placeholders.="?";
push(@$values, $value);
}
$dbh->prepare("INSERT INTO $table ($fields) VALUES ($placeholders)")->execute(@$values);
return $dbh->last_insert_id(undef, undef, undef, undef);
}
It assumes that $dbh
is a correctly initialized global database handle.
It is used like:
&insert("animals", {
"type"=>"cat",
"name"=>"Patches",
"date-of-birth"=>"November 1, 2015",
"date-of-death"=>undef
});
Which will insert a record into the animals table:
id | type | name | date-of-birth | date-of-death
=====================================================
1 | cat | Patches | November 1, 2015 | null