php - 在 MySQL PHP 中从多行结果中分离行
问题描述
对于下面的代码,$result 将从我的 question_answers 表中返回 4 行,它们具有相应的 question_id。
目前我正在将所有 4 行提取到 $answers 变量中。我想知道如何将每一行与结果分开并将它们存储为单独的变量,这样我就可以一次打印一个。
谢谢。
编辑:另外,由于 question_id 列是 question_answers 表和 $question["question_id"] 中的整数,我是否正确编写了 WHERE 语句?谢谢。
$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!");
}
解决方案
你可以这样做:
$i=1;
while(${"row" . $i} = mysqli_fetch_assoc($result)){$i++;};
因此,如果有 4 个结果,您将获得 $row1、$row2、$row3 和 $row4 中的行;
但更标准的方法是将行保存在数组中,然后使用数组:
while($rows[] = mysqli_fetch_assoc($result));
在这种情况下,您可以访问 $rows['0']、$rows['1']、$rows['2'] 和 $rows['3'] 等行
推荐阅读
- c++ - 如何用模板文件组织 C++ 目录,以及如何处理文件之间的#include 调用
- php - 使用 $_GET 发布 base64 编码图像时 URL 太长
- python - 如何使用 subprocess 为我的 Java 程序提供多个输入?
- google-calendar-api - Google 日历频道(事件:观看)的寿命有多长?
- java - 带有模拟上下文的 Volley 中的 NoClassDefFoundError
- google-apps-script - 导入 html 不适用于某些网站
- reactjs - 材料 ui 谷歌地图的地方
- java - 如何让我的 MouseListener 方法在 Java 中工作?
- javascript - 在滚动顶部闪烁
- flutter - 在 flutter_local_notifications 中添加 mp3 声音