At first I would like to thank markjugg for the tip with DBIx::Abstract.
I usually use the other INSERT syntax (similar to UPDATE, with SET).
Here comes an example:
sub db_store_event {
my $id = shift || 0;
my $ret = $id;
if ($id > 0) {
# update
my $hash = db_get_event($id);
my $event = impand_event(); # konvertiere Uhrzeit und Datum
my @update = ();
foreach my $key (keys %$hash) {
if (defined $event->{$key} and ($hash->{$key} ne $event->{
+$key})) {
push @update, $key.'='.$dbh->quote($event->{$key});
}
}
if (scalar @update > 0) {
db_do("UPDATE ".$config->{event_table}." SET ".join(', ',
+@update)." WHERE id=$id");
}
} else {
# insert
my $event = impand_event(); # konvertiere Uhrzeit und Datum
my @dat = ();
foreach my $key (keys %$event) {
push @dat, $key.'='.$dbh->quote($event->{$key}) if $event-
+>{$key};
}
my ($err, $sth) = db_sth("INSERT INTO ".$config->{event_table}
+." SET ".join(', ', @dat));
$ret = $sth->{'mysql_insertid'} or die "no db_id";
}
return $ret;
}
The routine impand_event() konverts the cgi parameter to an hashref with keys like the fields in the database and does some conversion (for date and time).
sub impand_event {
my ($datum, $zeit);
my %event = ();
foreach my $key ($cgi->param) {
if ($key =~ m/event\.(\w+)/) { $event{$1} = $cgi->param($key);
+ }
}
$datum = $event{datum_beginn};
if ($datum) { $event{datum_beginn} = date_to_sql($datum); }
$datum = $event{datum_ende};
if ($datum) { $event{datum_ende} = date_to_sql($datum); }
$zeit = $event{zeit_beginn};
if ($zeit) { $event{zeit_beginn} = time_to_sql($zeit); }
$zeit = $event{zeit_ende};
if ($zeit) { $event{zeit_ende} = time_to_sql($zeit); }
return wantarray ? %event : \%event;
}
Sorry for the german comments, but these are real lines of code.
uwevoelker
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.