2011-06-05 15 views
0

我目前從我的追隨者數據庫獲取accountID,並將它們輸出到JSON中。但不是隻是從數據庫中獲取accountID,我怎麼能從另一個表「Accounts」中獲取用戶信息並將其添加到JSON中?幫助使用用戶信息編碼JSON(MySQL)

我當前的代碼這樣做是:

$accountID = NULL; 
    if (isset($_GET['accountID'])) { 
     $accountID = mysql_real_escape_string($_GET['accountID']); 
    } 
    else { 
     exit("No accountID set"); 
    } 
    $query = mysql_query("SELECT * FROM Following WHERE `followingUserID` = '$accountID`"); 
    $rows = array(); 
    while($r = mysql_fetch_assoc($query)) { 
     $rows[] = $r; 
    } 
    header('Content-type: application/json'); 
    exit(json_encode($rows)); 

回答

2

我會去的肢體,並承擔了一些東西:

您有2個表:

followingId ,繼用戶ID,一些其他列

帳戶

用戶ID,someOtherAccountCollumns

鑑於這種情況,修復很簡單:

// Switch this: 
$query = mysql_query("SELECT * FROM Following WHERE `followingUserID` = '$accountID`"); 
// By this: 
$query = mysql_query(" 
    SELECT f.*, a.* 
    FROM Following as f 
    JOIN Accounts as a on f.followingUserID = a.userID 
    WHERE `f.followingUserID` = '$accountID` 
"); 

您將需要修改的列名,以正確的,但應該可以幫助您所有的帳戶信息的下表中的任何給定用戶。

祝你好運!

來源:

http://dev.mysql.com/doc/refman/5.1/en/join.html

+0

感謝您的代碼。我對後端開發很新,請你解釋一下代碼的作用? – 2011-06-05 17:51:58

+0

在原始的sql查詢中,您從一個表中選擇數據。使用JOIN允許您在多個表格之間關聯數據。因此,代碼的做法是:從表中選擇一行接下來,查找其FollowingUserId,然後使用JOIN語句,在帳戶中查找具有相同值的userID列中的行,將兩行關聯起來,因此您可以訪問帳戶表中有關該用戶標識的數據。 – Katsuke 2011-06-05 17:54:11