Reputation: 1430
I am trying to insert multiple values to the same field using a single query. Are there any mistakes in the following code?
my $dbh = DBI->connect("DBI:mysql:accounting:localhost", 'username', 'password',
{RaiseError => 1});
my @id = [1,18,976,90];
my @name = ['ss','dc','ws','rd'];
my @data = ([@id],[@name]);
my $ab = $dbh->prepare("insert into table (id,name) values (?,?)";);
for my $datam (@data) {
$ab->execute(@$datam);
}
$ab->finish();
I am getting the following error: DBI::st=HASH(0*a16f774)
for prepare statement. What could be causing this?
Upvotes: 1
Views: 94
Reputation: 386561
Can't really answer your question since you didn't actually give the error, but I have spotted a problem with your code. You're doing
$ab->execute([1,18,976,90]);
$ab->execute(['ss','dc','ws','rd']);
when you obviously want to do
$ab->execute( 1, 'ss');
$ab->execute( 18, 'dc');
$ab->execute(976, 'ws');
$ab->execute( 90, 'rd');
Fix:
my @id = (1,18,976,90);
my @name = ('ss','dc','ws','rd');
for my $i (0..$#id) {
$ab->execute($id[$i], $name[$i]);
}
Upvotes: 6
Reputation: 3465
I notice that your structure:
my @id = [1, 18, 976, 90];
is array with one element, which is array reference. You can check structure of variable by module Data::Dumper
. So you need only simple array:
my @id = (1, 18, 976, 90);
Using Data::Dumper
use Data::Dumper;
print Dumper( \@id );
$VAR1 = [
[
1,
18,
976,
90
]
];
Solution
use List::MoreUtils qw(each_array);
my @id = (1, 18, 976, 90);
my @name = ('ss', 'dc', 'ws', 'rd');
my $data = each_array(@id, @name);
...
while (my ($id, $name) = $data->()) {
$ab->execute($id, $name);
}
Upvotes: 3