如何使用PHP代码将SELECT结果插入到另一个表中?

时间:2019-02-18 11:52:25

标签: php

我有两个数据库,我正在尝试在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);
?>

运行此代码时,出现此错误:

  

致命错误:未捕获错误:调用成员函数execute()   第30行的C:\ wamp64 \ www \ Dashboard_Suporte \ replicador.php中的布尔值

1 个答案:

答案 0 :(得分:0)

您应该更改引爆以使用引号:

$sth = $connect2->prepare("INSERT INTO worklog ( " . implode('", "',array_keys($list)) . ") VALUES (" . implode('", "',array_keys($prep)) . ")");