PHP尝试将选择结果插入另一个db.table

时间:2019-02-15 10:32:26

标签: php mysql

我有两个数据库,我试图在db1.table1中执行SELECT并输入此select INTO db2.table2的结果。

已测试了与数据库的连接和SELECT之类的基本操作,我只需要帮助配置正确的方法即可将SELECT结果放入数组并将其输入db2.table2。

非常重要的一点是,我使用完全相同的名称命名SELECT列和db2.table2列,因此可以使用PHP中的IMPLODE命令。

您可以在下面看到我的代码:

<?php
//data to connect in both databases
require("connect_otrs_2.php");
require("connect_local_db.php");


//files with select queries
require("select_worklog.php");
require("select_backlog.php");

//connections to databases      
$connect=mysqli_connect($db_host,$db_user,$db_password,$db_name);
$connect2=mysqli_connect($db_localhost,$db_localuser,$db_localpassword,$db_localname);

//set utf8
mysqli_set_charset($connect, "utf8");
mysqli_set_charset($connect2, "utf8");

//the variable $qworklog contains the select from db1.table1, that I want insert into db2.table2
$worklog = mysqli_query($connect,$qworklog);


//this is my best try to insert values from $worklog select into the second database
while ($list = mysqli_fetch_assoc($worklog)){
    $prep = array();
    foreach($list as $k => $v) {
    $prep[':'.$k] = $v;
    }
    $sth = $connect2->prepare("INSERT INTO worklog ( " . implode(', ',array_keys($list)) . ") VALUES (" . implode(', ',array_keys($prep)) . ")");
    $res = $sth->execute($prep);

}

//close connection
mysqli_close($connect);
mysqli_close($connect2);
?>

0 个答案:

没有答案