【问题标题】:How to insert rows of a table from one database to another (with two PDO)如何将表的行从一个数据库插入到另一个数据库(使用两个 PDO)
【发布时间】:2018-10-09 12:06:15
【问题描述】:

我想插入我们网络数据库中显示的表的所有数据 在远程数据库上(存在于远程服务器上)

(此操作将每 30 分钟自动执行一次)

问题是我没有看到如何从 table_local 中检索所有数据并将它们直接插入 table_remote。

确实,连接这两个数据库,我用的是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 ?

?>

如果可能,我想避免使用foreach,因为脚本会经常启动,并且 table_local 包含很多行

有简单的解决办法吗?

【问题讨论】:

标签: php mysql database pdo sql-insert


【解决方案1】:

一种方法是使用像navicat或sequel pro这样的工具来实现。 另一种方法是使用以下代码:

$sql = "INSERT INTO table_name (column1, column2...) VALUES ";
foreach($res $key => $val) {
    $sql .= "($val['column1'],$val['column2']...),";
}
$sql = rtrim($sql, ',');
...

【讨论】:

  • 您的解决方案很好,但前提是我限制了第一个 select 否则我会出现此错误 Warning: PDOStatement :: execute (): MySQL server has gone away in .. on line 58 ($ request -&gt; execute ();) 为什么?
  • 对于这种情况,您可以尝试方法set_time_limit(0); ini_set('mysql.connect_timeout',300); ini_set('default_socket_timeout',300); 以避免在上面的代码中超时,另外,我认为您应该将order bylimit 添加到您的@ 987654330@sql,并用循环语句实现。
【解决方案2】:
<?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']]);


}

?>

参考链接https://phpdelusions.net/pdo_examples/insert

【讨论】:

    猜你喜欢
    • 2015-02-04
    • 2015-03-31
    • 1970-01-01
    • 2011-03-30
    • 1970-01-01
    • 1970-01-01
    • 2014-11-21
    • 2020-07-10
    • 1970-01-01
    相关资源
    最近更新 更多