内桌(1)
ID Name Address Phone InsertDate
1 Andrew 12-A,ABC 576849203 2014/05/06
1 Andrew 12-A,ABC 123456789 2014/07/08
内桌(2)
ID Name Address Phone InsertDate
1 Andrew 12-A,ABC 123456789 2014/07/08
我遇到的问题是
Select * from table(1) where id='1'
。它将检索两个记录。然后,当我尝试插入table(2)
时。它仅在表(2)中显示一条记录,而不是2条记录。我应该怎么做才能从table(1)获取两条记录并插入到table(2)?
我的示例代码:
$mysql="Select * from table(1) where id='1'";
**Perform the query**
**Retrieve values**
$sth->bind_col(1, \$Name);
$sth->bind_col(2, \$Address);
$sth->bind_col(3, \$Phone);
$sth->bind_col(4, \$InsertDate);
if($sth->fetch()){
$mysql="Insert into table(2) values($Name,$Address,$Phone,InsertDate)";
**Perform the query**
}
感谢您的观看,评论和答复!
最佳答案
您正在执行SELECT * FROM table(1)
,因此您正在提取所有列。第一个是ID
,因此您的列绑定不正确,并且很难相信您的代码甚至可以正确复制一条记录。另外,您只执行一次fetch
,因此,您只试图将两行之一插入table(2)
。
你需要写这样的东西
my $read = $dbh->prepare(<<'__END_SQL__');
SELECT Name, Address, Phone, InsertDate
FROM table(1)
WHERE ID = ?
__END_SQL__
my $write = $dbh->prepare(<<'__END_SQL__');
INSERT INTO table(2) (Name, Address, Phone, InsertDate)
VALUES (?, ?, ?, ?)
__END_SQL__
$read->execute(1);
while (my $row = $read->fetchrow_arrayref) {
$write->execute(@$row);
}
但是,除非有理由要在Perl级别上访问要复制的记录,否则可以让数据库为您完成所有操作,如下所示
my copy = $dbh->prepare(<<'__END_SQL__');
INSERT INTO table(2) (Name, Address, Phone, InsertDate)
SELECT Name, Address, Phone, InsertDate
FROM table(1)
WHERE ID = ?
__END_SQL__
$copy->execute(1);
关于mysql - 如何从数据库中检索多个值并将其设置为变量,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24529331/