Skip to content
PHP Logo

How can a loop in PHP be effectively used to compare and update data from two databases?

To compare and update data from two databases using a loop in PHP, you can fetch the data from both databases, iterate through the records, compare them based on a unique identifier, and update the data accordingly. You can use a loop to iterate through the records and perform the necessary comparisons and updates.

php
// Connect to the first database
$pdo1 = new PDO('mysql:host=localhost;dbname=database1', 'username', 'password');

// Connect to the second database
$pdo2 = new PDO('mysql:host=localhost;dbname=database2', 'username', 'password');

// Fetch data from the first database
$stmt1 = $pdo1->query('SELECT * FROM table1');
$data1 = $stmt1->fetchAll(PDO::FETCH_ASSOC);

// Fetch data from the second database
$stmt2 = $pdo2->query('SELECT * FROM table2');
$data2 = $stmt2->fetchAll(PDO::FETCH_ASSOC);

// Iterate through the records and compare/update data
foreach ($data1 as $row1) {
    foreach ($data2 as $row2) {
        if ($row1['id'] == $row2['id']) {
            // Update data in the second database based on comparison
            $stmt = $pdo2->prepare('UPDATE table2 SET column = :value WHERE id = :id');
            $stmt->execute(['value' => $row1['column'], 'id' => $row1['id']]);
        }
    }
}