I organized the withdrawal of questions from the database, but I can’t correctly write a query or function so that the answers on the question ID will be hooked to it. Now the question is displayed 4 times with each answer. How to fix it? Functions.php file

function getquestions ($conn){ $sql="SELECT questions.question_id,questions.question,answers.answer from questions LEFT JOIN answers ON questions.question_id=answers.question_id"; $result=$conn->query($sql); if ($result->num_rows>0){ while ($row=$result->fetch_assoc()){ $out[]=$row; } return $out; } } 

File test.php

 $data=getquestions($conn); foreach ($data as $testItem) { echo $testItem['question_id']. '. ' . $testItem['question']; echo '<br>'; echo $testItem['answer']; echo '<br>'; } 
  • Now the question is displayed 4 times with each answer. This is normal. Moreover, it is correct when getting the query result. Otherwise, how to determine which question is related to this or that answer? But when forming the result DISPLAY, you can delete these "duplicates". - Akina
  • @Akina I understand that the request was received correctly, and I just don’t understand how to display the result without duplicates, can you tell me how it is possible to do this? - Lisa
  • Look in the direction of Group by - Pavel Gribov

1 answer 1

 function getquestions ($conn){ $out = []; $sql="SELECT questions.question_id,questions.question,answers.answer from questions LEFT JOIN answers ON questions.question_id=answers.question_id"; $result=$conn->query($sql); while ($row=$result->fetch_assoc()){ $out[$row['question_id']]['question'] = $row; $out[$row['question_id']]['answers'][] = $row; } return $out; } 

File test.php

 $data = getquestions($conn); foreach ($data as $testItem) { echo $testItem['question']['question_id']. '. ' . $testItem['question']['question']; foreach ($testItem['answers'] as $answer) { echo '<br>'; echo $answer['answer']; echo '<br>'; } } 
  • Everything worked out! Thank you! - Lisa
  • I apologize for the stupid question, and how can I display the answer in the form of a radio button, so that the name is the question id, and the value id answer? - Lisa
  • @ Lisa echo '<label><input type="radio" name="question[' . $testItem['question']['question_id'] . ']" value="' . $answer['answer_id'] . '">' . $answer['answer'] . '</label>'; echo '<label><input type="radio" name="question[' . $testItem['question']['question_id'] . ']" value="' . $answer['answer_id'] . '">' . $answer['answer'] . '</label>'; - ArchDemon 3:17 pm