How can PHP be used to efficiently loop through a database table and save specific data in another table?

To efficiently loop through a database table and save specific data in another table using PHP, you can use a SELECT query to retrieve the data from the source table, iterate through the results using a loop, and then insert the desired data into the target table using an INSERT query within the loop.

// 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 specific data from source table
$sql = "SELECT id, name FROM source_table";
$result = $conn->query($sql);

// Loop through results and save specific data in target table
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        $id = $row["id"];
        $name = $row["name"];
        
        // Insert data into target table
        $insert_sql = "INSERT INTO target_table (id, name) VALUES ('$id', '$name')";
        $conn->query($insert_sql);
    }
} else {
    echo "0 results found";
}

// Close connection
$conn->close();