I have 3 different arrays in Perl (namely A, B and C). Now, I have a table in mysql which also has 3 fields.
What I am trying to do is get all the contents of array A in first field of mysql table, contents of array B into second field and so on. I tried doing this using foreach loops but it works fine for the first array but does not insert anything for the second and third array.
The code is used is as below:
foreach my $a (@a) {
my $sql = "insert into es(a) VALUES(\"$a\")";
my $sth = $dbh->prepare($sql);
$sth->execute or die "SQL Error: $DBI::errstr\n";
}
foreach my $b (@b) {
my $sql = "insert into es(b) VALUES(\"$b\")";
my $sth = $dbh->prepare($sql);
$sth->execute or die "SQL Error: $DBI::errstr\n";
}
and similarly for third.
The column a of the table gets populated correctly but there is no data for column b and c in the table. What am I doing wrong.
I guess you’re not very familiar with relational databases. What you’ve done is:
@a@aavalue in it; that means:@abandcareNULL.Now you do that for
@band@clikewise. That is not very efficient.DBI is designed to help you out here. You should consider the following rules (guidelines):
quotemethod or better placeholders. That saves you the hassle of addind quotes yourself.INSERTs orUPDATEs, alwaysprepareyour query outside of the loop and justexecuteit in the loop.Let’s take a look at your problem then. I assume
@a,@band@call have the same number of items, and you want one line per index of@a,@band@c. So if you have this data:My bet is that you want it to look like this in the db:
We therefore need to combine your three
INSERTs into one statement. That can be done by iterating over all of them at once. We can use theeach_arrayfunction from List::MoreUtils to handle the iteration for us. We’ll also add the guidelines from above to the code.