1 | initial version |
To transfer data from one table to another using PHP and SQL, you can follow these steps:
Connect to the database: Use the mysqli_connect() function or PDO to connect to the database.
Retrieve data from the source table: Use the SELECT statement to retrieve data from the source table.
Insert data into the target table: Use the INSERT INTO statement to insert the retrieved data into the target table.
Delete data from the source table (optional): Use the DELETE statement to delete the data from the source table after transferring it to the target table.
Example code:
<?php
// Connect to the database
$conn = mysqli_connect('localhost', 'username', 'password', 'database_name');
// Retrieve data from the source table
$sql = "SELECT * FROM source_table";
$result = mysqli_query($conn, $sql);
// Insert data into the target table
$sql = "INSERT INTO target_table (column1, column2, column3) VALUES ";
while ($row = mysqli_fetch_assoc($result)) {
$column1 = $row['column1'];
$column2 = $row['column2'];
$column3 = $row['column3'];
$sql .= "('$column1', '$column2', '$column3'), ";
}
$sql = rtrim($sql, ', ');
mysqli_query($conn, $sql);
// Delete data from the source table (optional)
$sql = "DELETE FROM source_table";
mysqli_query($conn, $sql);
mysqli_close($conn);
?>