在获取特定会话ID的所有匹配结果时遇到问题。我现在不想包括会话ID,但想包括所有其他结果(然后将在php中添加条件)。我只是得到一个ID(128)的行。因此,如果会话ID是125,则它排除了这一点,但只提取128,该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。
您的问题源于错误的缩进,导致您没有意识到将代码扔到哪里:它是否在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;
}