Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:
Here's what I currently have (that works) but I would like to better understand how placeholders could simplify the code. This is used to create a backup for a mySQL database (Part of a mySQL table editor)
If I could eliminate the need for the quotes, it would greatly simplify the 'download' code. I understand that, if I knew the number of fields in the table, I could use placeholders to add the quotes; but I don't because it can be any table in the database.# 1. Download text-only data. Comma delimited and quoted strings for +?easy? upload. my $table = $q->param('dbtable'); # Can be any table in the database my @field_type = (); my $n = 0; my $sth = $dbh->prepare("DESCRIBE $table"); $sth->execute(); while (my @field_descr = $sth->fetchrow_array) { @field_type[$n] = ($field_descr[1] =~ /char/i) ? 1 : 0; # Set to +1 if string $n++; } $sth->finish(); $sth = $dbh->prepare("SELECT * FROM $table"); $sth->execute(); print "Content-Type: text/plain\n\n"; while (my @record = $sth->fetchrow_array()) { # Build a string of each record, comma delimited, and inserting qu +otes as needed my ($recStr,$dl,$n) = ("","",0); foreach my $field (@record) { $field =~ s/(\n|\r)//g; # Get rid of any return chars that MAY + have been erroneously uploaded. $recStr .= ($field_type[$n]) ? "$dl'$field'" : "$dl$field"; # +Insert the quotes. $dl = ","; $n++; } print "$recStr\n"; } $sth->finish(); # 2. Upload the data. my $dbdata = $q->param('dbdata'); my @filedata = <$dbdata>; foreach my $record (@filedata) { my $sql = "INSERT INTO $table VALUES ($record)"; my $rows = $dbh->do($sql); }
Any ideas, thoughts, or comments would be appreciated and will, hopefully :), expand my limited Perl knowledgemy $sql = "INSERT INTO tablename VALUES(?,?,?,?)"; my $sth = $dbh->prepare($sql); foreach my $record (@filedata) { $sth->execute($fa,$fb,$fc,$fd); }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Understanding placeholders
by perlplexer (Hermit) on May 03, 2003 at 21:40 UTC | |
by nedals (Deacon) on May 04, 2003 at 16:21 UTC | |
|
Re: Understanding placeholders
by thraxil (Prior) on May 03, 2003 at 21:50 UTC | |
by perlplexer (Hermit) on May 03, 2003 at 22:04 UTC | |
by nedals (Deacon) on May 04, 2003 at 16:24 UTC | |
by dragonchild (Archbishop) on May 06, 2003 at 13:58 UTC | |
|
Re: Understanding placeholders
by BUU (Prior) on May 04, 2003 at 00:05 UTC | |
by nedals (Deacon) on May 04, 2003 at 16:35 UTC | |
|
Re: Understanding placeholders
by markjugg (Curate) on May 04, 2003 at 14:42 UTC | |
|
Re: Understanding placeholders
by crouchingpenguin (Priest) on May 04, 2003 at 19:49 UTC | |
|
Re: Understanding placeholders
by nedals (Deacon) on May 03, 2003 at 21:10 UTC |