What are the best practices for copying records from one table to another in PHP?
When copying records from one table to another in PHP, it is best practice to use SQL queries to retrieve the records from the source table and then insert them into the destination table. This can be achieved by selecting the records from the source table and then executing an INSERT query to add them to the destination table.
// Connect to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Select records from the source table
$sql = "SELECT * FROM source_table";
$result = $conn->query($sql);
// Insert records into the destination table
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$insert_sql = "INSERT INTO destination_table (column1, column2, column3) VALUES ('" . $row['column1'] . "', '" . $row['column2'] . "', '" . $row['column3'] . "')";
$conn->query($insert_sql);
}
}
// Close connection
$conn->close();
Keywords
Related Questions
- What are the potential challenges of modifying the array of fetched fields in PHP before generating an HTML table?
- How can new columns be generated from calculations based on input fields in a PHP form?
- How can PHP developers optimize performance when dealing with lengthy database queries and procedures that involve multiple joins across numerous tables?