如何在查询中检索多个结果(ID)

时间:2017-10-04 00:02:21

标签: php sql oop

我想检索多个结果,但目前只获得一个结果,这是我当前的代码:

$p_user = $prodata->user_id;
$usx = $user->getdb()->query("SELECT `user_one`, `user_two` FROM `friends` WHERE `user_one`= ? OR `user_two`= ? ", array($p_user, $p_user));

$count_frnds = $usx->count();
if(!$usx->count()){
    echo 'error';
}else {
    foreach($usx->results() as $use){
        $use->user_one;
        $use->user_two;
        if($p_user == $use->user_one){
            $can = $use->user_two;
        }else {
            $can = $use->user_one;
        }

     }
}

echo $can; //want multiple results, but only returns one result.

1 个答案:

答案 0 :(得分:0)

发条 - 缪斯已经指出了它。在你的foreach循环中,你用一个新值覆盖你的$ can,这就是为什么你只得到循环中的最后一个结果。首先尝试将$ can定义为数组。

$can = array();

...

foreach($usx->results() as $use){
    if($p_user == $use->user_one){
        $can[] = $use->user_two;
    }else {
        $can[] = $use->user_one;
    }
}

...

var_dump( $can );

// or

echo implode(",", $can);