有没有办法从另一个表插入记录

时间:2019-10-18 13:19:54

标签: php mysql

我想将下面的数据从表1复制到表2和表3中。

$query="INSERT INTO table2,table3 (st_id, name,reg)SELECT st_id,name,reg FROM table1";

2 个答案:

答案 0 :(得分:1)

$query2="INSERT INTO table2 (st_id, name,reg)SELECT st_id,name,reg FROM table1";
$query3="INSERT INTO table3 (st_id, name,reg)SELECT st_id,name,reg FROM table1";

答案 1 :(得分:-1)

<?php


// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}


// firstly select the data you want to copy

$sql_1 = "SELECT st_id,name,reg FROM table1";

$result = $conn->query($sql_1);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        $st_id = $row["st_id"];
        $name = $row["name"];
        $reg = $row["reg"]; 
    }

} else {
    echo "Not Found";
}


// secondly insert the data you select in the past

$stmt_1 = $conn->prepare("INSERT INTO table2 (st_id, name,reg) VALUES (?, ?, ?)");
$stmt_1->bind_param("iss", $st_id, $name, $reg);

$stmt_2 = $conn->prepare("INSERT INTO table3 (st_id, name,reg) VALUES (?, ?, ?)");
$stmt_2->bind_param("iss", $st_id, $name, $reg);

$stmt_1->execute();
$stmt_1->close();

$stmt_2->execute(); 
$stmt_2->close();

$conn->close();