簡體   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