无法获取特定会话ID的所有匹配结果。我想不包括会话ID,但现在包括所有其他结果(然后将在php中添加条件)。我只是获取一个ID(128)的行。因此,如果会话ID为125,则会将其排除在外但只会选取128,这是记录中的第一个,但是在三个128个条目(对于三个问题)之后是未包含的ID 127。当打印计数它告诉我3时,应该有6.所以我认为问题在函数内。
任何想法如何推动这一点?这是我的功能:
function quiz_match($user_id, $question_id ,$choice_id){
$query = mysqli_query($_POST['x'], "SELECT * FROM `question_answers` WHERE `user_id` <> $user_id AND `question_id` = $question_id AND `choice_id` = $choice_id" );
while($row = mysqli_fetch_assoc($query)){
$rows[] = $row;
if (count($rows)>0){
foreach ($rows as $key => $value) {
$u_id = $value['user_id'];
$array_q= [];
array_push($array_q, $u_id, $value['question_id'], $value['choice_id']);
//$result = count($array_q);
//echo "number of rows " . $result;
} return $array_q;
} else return false;
}
}
*对于数组[0],是ID,1问题ID和[2]选择ID。
答案 0 :(得分:2)
你的问题源于糟糕的缩进,导致你没有意识到你在哪里抛出代码:是否在while循环中,if,foreach,本来就是一个谜。
因此,在while循环中有if语句,因此从while循环中返回,而不是将所有行添加到$rows
数组,然后执行if语句。
如果您没有提前返回,那么您也可以将$array_q
重置为空,以便该行需要移出foreach
循环。
您也没有传递给该函数的MySQL连接!您正在将$_POST['x']
视为一个MySQL连接,并且它无法实现!
function quiz_match($connection, $user_id, $question_id ,$choice_id)
{
//there is no way the next commented out line even works!
//$query = mysqli_query($_POST['x'], "SELECT * FROM `question_answers` WHERE `user_id` <> $user_id AND `question_id` = $question_id AND `choice_id` = $choice_id" );
$query = mysqli_query($connection, "SELECT * FROM `question_answers` WHERE `user_id` <> $user_id AND `question_id` = $question_id AND `choice_id` = $choice_id");
$rows = array(); //you should add this too
while($row = mysqli_fetch_assoc($query))
{
$rows[] = $row;
}
if (count($rows)>0)
{
$array_q = array(); //this should be here, not in the foreach loop
foreach ($rows as $key => $value)
{
$u_id = $value['user_id'];
//$array_q= []; //wrong place for this
array_push($array_q, $u_id, $value['question_id'], $value['choice_id']);
}
//$result = count($array_q);
//echo "number of rows " . $result;
return $array_q;
}
return false;
}