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

Php 帮助使用用户信息编码JSON(MySQL),php,mysql,database,json,Php,Mysql,Database,Json,我目前正在从我的追随者数据库获取accountID,并将其输出到JSON中。但是,我如何从另一个表“Accounts”中获取用户信息并将其附加到JSON中,而不仅仅是从db中获取accountID 我目前的代码是: $accountID = NULL; if (isset($_GET['accountID'])) { $accountID = mysql_real_escape_string($_GET['accountID']); } else

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

我目前的代码是:

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

我会冒险做一些假设:

您有两个表:

跟随

followerID、followerUserID、someOtherColumns

帐目

用户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`
");
您需要将列名修改为正确的列名,但这将有助于您获得下表中任何给定用户的所有帐户信息

祝你好运

资料来源:


谢谢您的代码。我对后端开发非常陌生,请您解释一下代码的作用好吗?在原始sql查询中,您是从单个表中选择数据的。使用JOIN可以在多个表之间关联数据。因此,代码所做的是:从表Following中选择一行,查找其followinuserid,然后使用JOIN语句,在Accounts中查找userID列中具有相同值的行,将这两行关联起来,从而使您能够访问Accounts表中关于该userID的数据。