【问题标题】:Separate rows from a multi-row result in MySQL PHP在 MySQL PHP 中从多行结果中分离行
【发布时间】:2021-10-18 20:14:36
【问题描述】:

对于下面的代码,$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!");
}

【问题讨论】:

  • 不,sql 注入很脆弱,请参阅stackoverflow.com/questions/60174/… 以获得指导
  • @nbk 谢谢,但这并不能真正回答我的问题。我想知道代码是否有效。你也忽略了我帖子的要点。
  • 你真的应该读到最后,记住要复制

标签: php mysql sql


【解决方案1】:

你可以这样做:

$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'] 等行

【讨论】:

  • 你应该提到sql注入问题
  • @sultan 谢谢你,我会试试这个。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-03
  • 1970-01-01
相关资源
最近更新 更多