If you want to move the contents of one table to another table whose fields are exactly the same, use the following steps:
- Connect to a MySQL database and select the database you want to operate on.
$db = mysqli_connect("localhost", "username", "password", "my_database"); mysqli_select_db($db, "my_database"); - Select the data to move from the source table. You can use
SELECTstatement to select the data to move, as follows:$result = mysqli_query($db, "SELECT * FROM source_table WHERE condition");In the above statement,
source_tableis the table name of the source table,conditionis the condition for selecting data. - Inserts selected data into the target table. You can use
INSERT INTOThe statement inserts data into the target table as follows:while ($row = mysqli_fetch_assoc($result)) { $values = implode("', '", $row); mysqli_query($db, "INSERT INTO target_table VALUES ('$values')"); }In the above statement,
target_tableis the table name of the target table,$rowis an associative array of one row of data,$valuesIs a string of array values separated by commas. Since the table fields are exactly the same, we can directly useINSERT INTOstatement to insert data into the target table. - Close the database connection.
mysqli_close($db);
The complete PHP code looks like this:
$db = mysqli_connect("localhost", "username", "password", "my_database");
mysqli_select_db($db, "my_database");
$result = mysqli_query($db, "SELECT * FROM source_table WHERE condition");
while ($row = mysqli_fetch_assoc($result)) {
$values = implode("', '", $row);
mysqli_query($db, "INSERT INTO target_table VALUES ('$values')");
}
mysqli_close($db);In the above code you need to put source_table 和 target_table with the actual table name and replace condition Replace with a condition for selecting the data. In addition, please note that the code needs to be adjusted and optimized according to the specific situation in the actual use.