繁体   English   中英

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

[英]Is there a way to insert record from another table

我希望将数据从 table1 复制到 table2 和下面的 table3 是我尝试过的。

$query="INSERT INTO table2,table3 (st_id, name,reg)SELECT st_id,name,reg FROM table1";
$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";
<?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();

暂无
暂无

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

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