内表(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条记录。
我该怎么做才能从表(1)中获取两条记录并插入表格(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**
}
感谢您查看,评论和解答!
答案 0 :(得分:2)
您正在执行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);
答案 1 :(得分:-1)
首先要确保table2,id或name或其他某些字段未设置为primary或不允许你插入重复记录..
试试这个PHP代码......
result=mysql_query(" select * from table where id=1 ");
while($row=mysql_fetch_assoc($result))
{
$name=$row["Name"];
$address==$row["address"];
$phone==$row["phone"];
$insertdate=$row["insertdate"];
mysql_query( "insert into table2(name,address,phone,insertdate) values('$name','$address','$phone','$insertdate') ");
}