[英]How to insert rows of a table from one database to another (with two PDO)
I would like to insert all the data of a table presented on the database of our network on a remote database (present on a remote server) 我想将呈现在网络数据库中的表的所有数据插入到远程数据库(存在于远程服务器中)中
(this action will automate every 30 minutes) (此操作将每30分钟自动执行一次)
The problem is that I do not see how to retrieve all the data from the table_local and insert them directly into the table_remote. 问题是我看不到如何从table_local中检索所有数据并将其直接插入table_remote中。
Indeed, to connect to these two databases, I use PDO 确实,要连接到这两个数据库,我使用PDO
<?php
// LOCAL
$user = 'user1';
$password = 'password1';
$dns = 'completeDNS1';
$bdd = new PDO($dns, $user, $password);
$request = $bdd->prepare("SELECT * FROM table_local");
$request ->execute();
// REMOTE
$user = 'user2';
$password = 'password2';
$dns = 'completeDNS2';
$bdd = new PDO($dns, $user, $password);
// How to insert the previous data on the table_remote ?
?>
I would like to avoid, if possible, the foreach
because the script will be launched very often and the table_local contains a lot of line 如果可能的话,我想避免使用foreach
因为脚本将非常频繁地启动,并且table_local包含很多行
Is there a simple solution? 有没有简单的解决方案?
One method is using one tool like navicat or sequel pro to achieve. 一种方法是使用navicat或sequel pro这样的工具来实现。 Another method is using following codes: 另一种方法是使用以下代码:
$sql = "INSERT INTO table_name (column1, column2...) VALUES ";
foreach($res $key => $val) {
$sql .= "($val['column1'],$val['column2']...),";
}
$sql = rtrim($sql, ',');
...
<?php
// LOCAL
$user = 'user1';
$password = 'password1';
$dns = 'completeDNS1';
$bdd1 = new PDO("mysql:host=localhost;dbname=$dns", $user, $password);
$user = 'user2';
$password = 'password2';
$dns = 'completeDNS2';
$bdd2 = new PDO("mysql:host=localhost;dbname=$dns", $user, $password);
$request = $bdd1->prepare("SELECT * FROM table_local");
// REMOTE
while ($row = $request->fetch()) {
$sql = "INSERT INTO table_remote (name, surname, sex) VALUES (?,?,?)";
$stmt= $bdd2->prepare($sql);
$stmt->execute([$row['name'], $row['surname'], $row['sex']]);
}
?>
for reference check this link https://phpdelusions.net/pdo_examples/insert 供参考,请检查此链接https://phpdelusions.net/pdo_examples/insert
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.