Are there any best practices for copying data from one table to another in PHP using SQL queries?

When copying data from one table to another in PHP using SQL queries, it is best practice to use the INSERT INTO ... SELECT statement. This statement allows you to select data from one table and insert it into another table in a single query, which can be more efficient than fetching data in PHP and then inserting it row by row.

<?php
// Establish a connection to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

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

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

// Copy data from table1 to table2
$sql = "INSERT INTO table2 (column1, column2, column3)
        SELECT column1, column2, column3
        FROM table1";

if ($conn->query($sql) === TRUE) {
    echo "Data copied successfully";
} else {
    echo "Error copying data: " . $conn->error;
}

// Close the connection
$conn->close();
?>