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); }
In reply to Understanding placeholders by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |