How can PHP be used to retrieve data from one table and insert it into another table in a relational database?
To retrieve data from one table and insert it into another table in a relational database using PHP, you can first fetch the data from the source table using a SELECT query and then insert that data into the target table using an INSERT query.
<?php
// Connect to the database
$pdo = new PDO('mysql:host=localhost;dbname=database_name', 'username', 'password');
// Retrieve data from the source table
$stmt = $pdo->prepare("SELECT * FROM source_table");
$stmt->execute();
$data = $stmt->fetchAll();
// Insert data into the target table
foreach($data as $row) {
$insertStmt = $pdo->prepare("INSERT INTO target_table (column1, column2, column3) VALUES (:value1, :value2, :value3)");
$insertStmt->execute(array(
'value1' => $row['column1'],
'value2' => $row['column2'],
'value3' => $row['column3']
));
}
echo "Data transferred successfully!";
?>