2011-04-09 24 views
3

我正在處理從一個數據庫到另一個數據庫的導入功能,並認爲我會嘗試構建Mysqli功能。Mysqli準備對多個數據庫的報表

我已經打開了兩個連接,每個數據庫一個連接,並且在選擇是否插入數據之前循環舊連接(獲取現有用戶)並在新連接上運行檢查。

現在我不確定是否濫用了準備報表功能,或者我無法獲得正確的結果。一個簡單的測試案例是:

 
$oldDB = new Mysqli(HOST, USER, PASS, 'oldDB'); 
$newDB = new Mysqli(HOST, USER, PASS, 'newDB'); 

/* 
* Prepared statments 
*/ 
$searchUserStmt = $newDB->prepare('SELECT user_id FROM members WHERE user_id=?'); 
$searchUserStmt->bind_param('i', $old_user_id); 
$searchUserStmt->bind_result($user_id); 

/** 
* Loop through users 
*/ 
$result = $oldDB->query('SELECT * FROM member_profile LIMIT 10'); 
while($row = $result->fetch_assoc()) 
{ 

    var_dump($row['user_id']); 

    // Check if user is already in DB 
    $old_user_id = $row['user_id']; 
    $searchUserStmt->execute(); 

    $searchUserStmt->fetch(); 
    $searchUserStmt->reset(); 
    var_dump($user_id); 

}

當我在$newDB仰望user_id用事先準備好的聲明它只返回的第一個結果的user_id我上$oldDB第一查詢運行良好,並遍歷用戶不過。

這裏的輸出我得到的一個樣本:

 
string(1) "1" 
int(1) 
string(2) "31" 
int(1) 
string(2) "26" 
int(1) 
string(3) "105" 
int(1) 
string(2) "34" 
int(1) 
string(3) "119" 
int(1) 
string(2) "36" 
int(1) 
string(2) "37" 
int(1) 
string(2) "38" 
int(1) 
string(2) "39" 
int(1) 

沒有人有任何知道我做錯了嗎?我已經通過Mysqli文檔,但沒有找到任何幫助我的東西。

回答

2

好吧,我發現這個問題,事情工作正常,但看起來mysqli_stmt::bind_result()中使用的變量沒有得到更新,除非找到一行。在我的測試中,只有第一個用戶被發現導致每次都返回1。

mysqli_stmt::fetch()將返回NULL時找不到結果,所以我只是有稍微修改我的代碼如下所示:

 
while($row = $result->fetch_assoc()) 
{ 

    var_dump($row['user_id']); 

    // Check if user is already in DB 
    $old_user_id = $row['user_id']; 
    $searchUserStmt->execute(); 

    if($searchUserStmt->fetch() === NULL) 
    { 
     // Insert user here 
    } 
    $searchUserStmt->reset(); 

}