What is the best way to copy SQL records from one table to another in PHP while ensuring data integrity and security?

When copying SQL records from one table to another in PHP, it is important to ensure data integrity and security. One way to achieve this is by using prepared statements to prevent SQL injection attacks and by validating the data before inserting it into the new table. Additionally, it is recommended to use transactions to ensure that the data is copied completely or not at all.

<?php
// Establish a connection to the database
$pdo = new PDO('mysql:host=localhost;dbname=your_database', 'username', 'password');

// Begin a transaction
$pdo->beginTransaction();

// Prepare the SQL query to select records from the source table
$sourceRecords = $pdo->prepare('SELECT * FROM source_table');

// Execute the query
$sourceRecords->execute();

// Prepare the SQL query to insert records into the destination table
$insertRecord = $pdo->prepare('INSERT INTO destination_table (column1, column2) VALUES (:column1, :column2)');

// Loop through the selected records and insert them into the destination table
while ($record = $sourceRecords->fetch(PDO::FETCH_ASSOC)) {
    $insertRecord->bindParam(':column1', $record['column1']);
    $insertRecord->bindParam(':column2', $record['column2']);
    $insertRecord->execute();
}

// Commit the transaction
$pdo->commit();

// Close the connection
$pdo = null;
?>