json响应中的多个结果数据

时间:2019-03-29 18:35:50

标签: php

我是PHP的新手,正在尝试构建一个API,该API向我提供所需数据的json响应。那里有一张名为user的表,我需要其中的电子邮件,用户名和user_type。我已经像下面这样编码了

$result = array();
$users = getOnlineUsers($conn);
    $userinfo['email'] = $users['email'];
    $userinfo['username'] = $users['username'];
    $userinfo['user_type'] = $users['user_type'];
    $result['status'] ="success";
    $result['userData'] = $userinfo;

功能如下所示

function getOnlineUsers($conn)
    {
        $q  = $conn->prepare("SELECT * FROM table_users WHERE online_status = 1");
       // $q->bind_param("s", $email);
        $q->execute();


        $result = $q->store_result();
        $metaResults = $q->result_metadata();
        $fields = $metaResults->fetch_fields();
        $statementParams='';
         foreach($fields as $field){
             if(empty($statementParams)){
                 $statementParams.="\$column['".$field->name."']";
             }else{
                 $statementParams.=", \$column['".$field->name."']";
             }
        }
        $statment="\$q->bind_result($statementParams);";
        eval($statment);
        $q->fetch();

        return $column;
    }

它工作正常,但只给了我一行。我要得到所有行而不是一行。我正在收到这样的回复

{"status":"success","userData":{"email":"abc@gmail.com","username":"rajrathodbvn","user_type":0}}

让我知道是否有人可以帮助我解决我的问题。 谢谢

1 个答案:

答案 0 :(得分:2)

对于这么简单的事情,有很多代码。选择所需的列:

function getOnlineUsers($conn) {
    $q = $conn->prepare("SELECT email, username, user_type
                                FROM table_users
                                WHERE online_status = 1");
    $q->execute();
    return $q->fetchAll(PDO::FETCH_ASSOC);
}

然后分配:

$result['status'] = 'success';
$result['userData'] = getOnlineUsers($conn);

或者:

$result = ['status' => 'success', 'userData' => getOnlineUsers($conn)];