帮助使用用户信息(MySQL)编码JSON

时间:2011-06-05 17:37:46

标签: php mysql database json

我目前从我的关注者数据库获取accountID并将其输出到JSON。但是,我不是从数据库中获取accountID,而是如何从另一个表“Accounts”获取用户信息并将其附加到JSON?

我目前的代码是:

    $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));

1 个答案:

答案 0 :(得分:2)

我会继续下去并假设一些事情:

你有两张桌子:

followId,followUserID,someOtherColumns

帐户

userID,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