简体   繁体   English

MySQL 将表复制到具有相同凭据的不同数据库

[英]MySQL copy table to different database with same credentials

I am using the standard MySQL functions that PHP has built in for copying one table to an new table.我正在使用 PHP 内置的标准 MySQL 函数将一个表复制到一个新表。 This works perfect when the tables are in the same database.当表在同一个数据库中时,这很完美。 But I want to copy it to another databasename with same user and password.但我想将它复制到另一个具有相同用户和密码的数据库名。

Any suggestions how to achive this?任何建议如何实现这一目标? (Since $database can only contain 1 databasename) (因为$database只能包含 1 个数据库名)

Error shown is Table 'torzahttp_rsw.torzahttp_rsw.kwaliteit' doesn't exist torzahttp_rsw is the database name, and kwaliteit the table name.显示的错误是Table 'torzahttp_rsw.torzahttp_rsw.kwaliteit' doesn't exist torzahttp_rsw是数据库名称, kwaliteit是表名称。 Why is the databasename used twice?为什么数据库名被使用了两次?

// Create a new MySQL database connection
if (!$con = new mysqli('localhost', $username, $password, $database)) {
    die('An error occurred while connecting to the MySQL server!<br><br>' . $con->connect_error);
}

// Create an array of MySQL queries to run
$sql = array(
    'DROP TABLE IF EXISTS `backup_db.backup_table`;',
    'CREATE TABLE `backup_db.backup_table` SELECT * FROM `live_db.live_table`'
);

// Run the MySQL queries
if (sizeof($sql) > 0) {
    foreach ($sql as $query) {
        if (!$con->query($query)) {
            die('A MySQL error has occurred!<br><br>' . $con->error);
        }
    }
}

$con->close();

From the MySQL manual :MySQL 手册

If any components of a multiple-part name require quoting, quote them individually rather than quoting the name as a whole.如果多部分名称的任何组成部分需要引用,请单独引用它们,而不是引用整个名称。 For example, write `my-table`.`my-column` , not `my-table.my-column` .例如,写`my-table`.`my-column` ,而不是`my-table.my-column`

Your code:您的代码:

$sql = array(
    'DROP TABLE IF EXISTS `backup_db.backup_table`;',
    'CREATE TABLE `backup_db.backup_table` SELECT * FROM `live_db.live_table`'
);

should look like this:应该是这样的:

$sql = array(
    'DROP TABLE IF EXISTS `backup_db`.`backup_table`;',
    'CREATE TABLE `backup_db`.`backup_table` SELECT * FROM `live_db`.`live_table`'
);

Or, just drop the backticks altogether.或者,完全删除反引号。

I have used this solution to create an mysql dump first and then processioning it.我已使用此解决方案先创建一个 mysql 转储,然后对其进行处理。

//DB 
$user = 'xxxxx';
$password = 'xxxxx';
$host = 'localhost';
$database_old = 'old_db';
$database_new = 'new_db';

$table = 'kwaliteit';
$file = 'kwaliteit.sql';

exec('mysqldump --user='.$user.' --password='.$password.' --host='.$host.' '.$database_old.' '.$table.' > uploads/'.$file);

exec('mysql --user='.$user.' --password='.$password.' --host='.$host.' '.$database_new.' < uploads/'.$file);

unlink('uploads/'.$file);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM