Ask Your Question
3

How can I transfer data from one table to another using PHP and SQL?

asked 2022-02-11 11:00:00 +0000

scrum gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2021-08-06 20:00:00 +0000

djk gravatar image

To transfer data from one table to another using PHP and SQL, you can follow these steps:

  1. Connect to the database: Use the mysqli_connect() function or PDO to connect to the database.

  2. Retrieve data from the source table: Use the SELECT statement to retrieve data from the source table.

  3. Insert data into the target table: Use the INSERT INTO statement to insert the retrieved data into the target table.

  4. 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);
?>
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-02-11 11:00:00 +0000

Seen: 11 times

Last updated: Aug 06 '21