简体   繁体   English

在 MySQL PHP 中从多行结果中分离行

[英]Separate rows from a multi-row result in MySQL PHP

For the code below, $result will return 4 rows from my question_answers table which have the corresponding question_id.对于下面的代码,$result 将从我的 question_answers 表中返回 4 行,这些行具有相应的 question_id。

At the moment I am fetching all 4 rows into the $answers variable.目前我正在将所有 4 行提取到 $answers 变量中。 I was wondering how I could separate each row from the result and store them as separate variables so I could, say, printf them one at a time.我想知道如何将每一行与结果分开并将它们存储为单独的变量,以便我可以一次打印一个。

Thanks.谢谢。

Edit: also, since the question_id column is an integer in the question_answers table and also in $question["question_id"], have I written my WHERE statement correctly?编辑:此外,由于 question_id 列是 question_answers 表和 $question["question_id"] 中的整数,我是否正确编写了我的 WHERE 语句? Thanks.谢谢。

$result = mysqli_query($connection, 'SELECT  FROM questions_answers WHERE question_id='".$question["question_id"]."' ORDER BY RAND()'); //Runs the select query to get the possible answers to the randomly selected question
if(mysqli_num_rows($result)>0){
    $answers = mysqli_fetch_assoc($result);
    //printf each row individually
}
else{
    printf("ERROR: no answers for this question exist!");
}

You can do this like below:你可以像下面这样做:

$i=1;    
while(${"row" . $i} = mysqli_fetch_assoc($result)){$i++;};

So if there are 4 results, you will get the rows in $row1, $row2, $row3 and $row4;因此,如果有 4 个结果,您将获得 $row1、$row2、$row3 和 $row4 中的行;

But more standard way is to save the rows in array and use the array afterwards:但更标准的方法是将行保存在数组中,然后使用该数组:

while($rows[] = mysqli_fetch_assoc($result));

In this case, you can access the rows like $rows['0'], $rows['1'], $rows['2'] and $rows['3']在这种情况下,您可以访问 $rows['0']、$rows['1']、$rows['2'] 和 $rows['3'] 等行

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM