使用 SELECT * INTO 将记录复制到另一个数据库

问题描述 投票:0回答:1

我正在尝试将一个数据库中的表复制到另一个数据库中。原始表包含静态数据。我需要能够操作“复制表”中的数据。这个过程需要是动态的,因为我将生成多个副本,每个用户一个。

目前我正在 PHP 调用中使用此代码。它的意思是加载相关数据表,选择表中的所有数据,然后使用

$Player
变量作为新表名在player_missions 数据库中创建一个新表。

define('HOSTNAME','localhost:3306');  
define('DB_USERNAME','root');  define('DB_PASSWORD','');
define('DB_NAME','geo_locations');  global $conn;
$conn = mysqli_connect(HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_NAME) or die ("error");
  
$Player=$_SESSION["Player_ID"]; $geo_loc='C3B3';

$sql="SELECT * INTO $Player IN 'player_missions.mdb' FROM $geo_loc";

if(mysqli_query($conn, $sql)){} else{echo "ERROR: Was not able to execute $sql. " . mysqli_error($conn);}

我相信你可以看出,我的 SQL 知识相当贫乏,但我为寻找解决方案所做的长期努力却没有取得成果。

这是错误消息:

ERROR: Was not able to execute SELECT * INTO 
805361725171703141241123 IN 'player_missions.mdb' FROM C3B3. You
have an error in your SQL syntax; check the manual that 
corresponds to your MariaDB server version for the right syntax 
to use near '805361725171703141241123 IN 'player_missions.mdb' 
FROM C3B3' at line 1

我访问过W3和其他网站但无法解决。

sql database insert
1个回答
0
投票
To copy data from one table to another, MySQL syntax doesn’t support the SELECT * INTO statement with an external database in the way it's currently structured. Instead, you need to use CREATE TABLE with SELECT or INSERT INTO for the data transfer. Below is the revised code:

<?php
// Database connection settings
define('HOSTNAME', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_NAME', 'geo_locations');

// Connect to the primary database
$conn = mysqli_connect(HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_NAME) or die("Connection error: " . mysqli_connect_error());

// Get player ID from session and original table name
$Player = $_SESSION["Player_ID"];
$geo_loc = 'C3B3';

// Set the new database and table name dynamically
$new_db = 'player_missions';
$new_table = $Player;

// Step 1: Create the new table in the target database
$createTableSQL = "CREATE TABLE `$new_db`.`$new_table` LIKE `$geo_loc`";

if (mysqli_query($conn, $createTableSQL)) {
    echo "Table created successfully. ";
} else {
    echo "Error creating table: " . mysqli_error($conn);
    exit;
}

// Step 2: Insert data from the original table into the new table
$insertDataSQL = "INSERT INTO `$new_db`.`$new_table` SELECT * FROM `$geo_loc`";

if (mysqli_query($conn, $insertDataSQL)) {
    echo "Data copied successfully!";
} else {
    echo "Error copying data: " . mysqli_error($conn);
}

mysqli_close($conn);
?>


Table Creation: We dynamically set the table name with the $Player variable and use the SQL statement:

CREATE TABLE `new_db`.`new_table` LIKE `geo_loc`

This creates a new table in the player_missions database with the same structure as the geo_loc table but does not copy data.
© www.soinside.com 2019 - 2024. All rights reserved.