2011-01-10 94 views
0

我需要從兩個獨立服務器上的兩個單獨的數據庫中檢索數據(用戶名和電子郵件地址),並檢查用戶名是否僅存在於一側而不是另一側,並顯示結果爲表。從我的研究中,不可能在mySQL中進行跨服務器查詢,所以我試圖在PHP中完成所有操作,但是我陷入了沒有結果的困境,而且我的代碼變得無法讀取。主要問題是我需要輸出與用戶名相關聯的電子郵件地址,但只有第一個數據庫具有用戶名和電子郵件地址列表。我確信我的算法完全沒有效率,我很想看到一些簡單的解決方案。使用PHP比較來自不同服務器的兩個表格

$handle1 = mysql_connect($db_host1,$db_username1,$db_password1); 
mysql_select_db($db_name, $handle1); 

$query1 = "SELECT username, email, FROM tblservices"; 
$result1 = mysql_query($query1); 

while($row = mysql_fetch_array($result1){ 
$arr1[]=array(username=>$row['username'],email=>$row['email']);} 

$handle2 = mysql_connect($db_host2,$db_username2,$db_password2); 
mysql_select_db($db_name, $handle2); 

$query2 = "SELECT username from tblradius"; 
$result2 = mysql_query($query2, $handle2); 

while($row = mysql_fetch_array($result2)){ 
    $arr2[]=$row['username']; 
} 


echo "<p>List of users in DB1 and not DB2</p>"; 

$x=0; 
foreach($arr1 as $row1) { 
    $user1=$row1['username']; 
    $email=$row1['email']; 
     foreach($arr2 as $user2) { 
      if ($user1==$user2) { 
       $x=1; 
      } 
     } 
     if ($x==0) { 
      echo "<p>$user1 - $email is not in DB2</p>"; 
     } 
    $x=0; 
    } 
} 

echo "<p>List of users in DB2 and not DB1</p>"; 

$x=0; 
foreach($arr2 as $user1) { 
    foreach($arr1 as $row2) { 
     $user2=$row2['username']; 
     if ($user1==$user2) { 
      $x=1; 
     } 
    } 
    if ($x==0) { 
     foreach($arr2 as $row3) { 
      $user3 = $row3['username']; 
      $email = $row3['email']; 
      if ($user1==$user3) { 
       echo "<p>$user3 $email - is in DB2 and not DB1</p>"; 
      } 
     } 
    } 
    $x=0; 
} 

}

回答

1

像這樣的東西應該做的伎倆

//connect and query DB1 

while($row = mysql_fetch_assoc($result1)) { 
    $users[$row['username']] = $row['email']; 
} 

//Connect and query DB2 

while($row2 = mysql_fetch_assoc($result2)) { 
    if(isset($users[$row2['username']])) { 
     unset($users[$row2['username']]); 
    } else { 
     $db2users[$row2['username']] = "No mail given for user"; 
    } 
} 

foreach($users as $username => $email) { 
    echo $username . " - " . $email . " does not exist in DB2"; 
} 
foreach($db2users as $db2username => $db2email) { 
    echo $db2username . " - " . $db2email . " does not exist in DB1"; 
} 

它所做的是它增加了所有用戶提供第一次查詢到一個數組,然後如果他們的存在將其刪除第二個陣列基於數組鍵,這使得性能也很好。

最終數組將包含DB1中但不存在於DB2中的所有用戶的名稱和郵件。

如果您已經擁有這些連接並查詢數據庫,請將其排除在外。