我正在使用PDO(mysql)创建2个不同的数据库连接。我想在一个不同的数据库中将一行数据从一个表传输到另一个表。这不是行的重复,只选择了某些行。
我无法让它发挥作用,任何想法?
private function moveCallToProduction() {
try {
$sql = "SELECT * FROM `calls` WHERE `id`=':id'";
$query = $this->staging->prepare($sql);
$query->execute($array);
$results = $query->fetchAll(PDO::FETCH_ASSOC);
try {
$sql = "INSERT INTO `calls` (`id`,`sip_id`,`extension`,`caller_id`,`stage`,`status`,`survey_id`,`start`,`answer`,`hangup`,`end`) VALUES ('?','?','?','?','?','?','?','?','?','?','?')";
$query = $this->production->prepare($sql);
$query->execute($results);
}
catch(PDOException $e) {
$this->informer("FATAL","There was a problem");
}
}
catch(PDOException $e) {
$this->informer("FATAL","We're unable to transport the call from the staging to production server. Error: ".$e->getMessage());
}
}
答案 0 :(得分:5)
fetchAll()
返回包含所有结果集行的数组。您需要迭代每一行并单独插入它。例如:
...
$sql = "SELECT * FROM `calls` WHERE `id`=':id'";
$query = $this->staging->prepare($sql);
$query->execute($array);
$results = $query->fetchAll(PDO::FETCH_ASSOC);
foreach($results as $row) {
try {
$sql = "INSERT INTO `calls` (`id`,`sip_id`,`extension`,`caller_id`,`stage`,`status`,`survey_id`,`start`,`answer`,`hangup`,`end`) VALUES ('?','?','?','?','?','?','?','?','?','?','?')";
$query = $this->production->prepare($sql);
$query->execute($row);
}
catch(PDOException $e) {
$this->informer("FATAL","There was a problem");
}
}
...
您还可以使用语句while($result = $query->fetch(PDO::FETCH_ASSOC))
代替fetchAll()
来迭代结果,而不必将其存储在内存中。
要考虑的一件事是,如果遇到异常,您想要做什么。由于您要多次插入,因此可以考虑在开头使用PDO::beginTransation()
,如果没有异常则使用PDO::commit()
,如果发生异常,则PDO::rollBack()
取消任何更改。通过这种方式,您可以确保一切都可以转移,也可以不做任何事情。