0

I am having a problem of data looping here. Basically the questions keep looping whenever there are answers for it . I am trying to display something like :

Question 
Answer 1  
Answer 2 
Answer 3

instead of

Question 
Answer 1

Question
Answer 2

Question
Answer 3

Anyone know how to solve this ?

<?php
$auctionSurvey = "SELECT questions.question_id, answers.question_id, answers.survey_id, question_body, answer_body FROM questions
                  INNER JOIN answers ON answers.question_id = questions.question_id
                  WHERE answers.survey_id='1'";
$aucResult = mysql_query($auctionSurvey) or die (mysql_error());

while ($auctionRow = mysql_fetch_assoc($aucResult)) {
    echo $auctionRow['question_body'] . $auctionRow['answer_body'];
}
1
  • Because that's how JOINs work. If your data maps between tables A and B in an n:m relationship you'll have n copies of B's data, m copies of A's data, and n*m total rows. You have to write the logic in PHP to deal with it. Commented Dec 18, 2013 at 19:32

1 Answer 1

1
$questionId = 0;
while($auctionRow = mysql_fetch_assoc($aucResult)){
   if($auctionRow['question_id'] != $questionId){
        echo $auctionRow['question_body'];
        $questionId = $auctionRow['question_id'];
   }  
   echo $auctionRow['answer_body'];
}

Add some HTML to format it and that should work for ya.

Edit: Proof: http://ideone.com/Gkq2hd

Sign up to request clarification or add additional context in comments.

8 Comments

This only displays answer_body right? How do I actually make the questions don't loop? Question Answer 1 Answer 2 Answer 3 instead of Question Answer 1 Question Answer 2 ...
Did you try it? Did you even read the code? You just asked your question again in response to my answer.
Yeah I did try . It only shows the answers. I tried echoing question_body but doesn't seem to work.
Well, it should work, so there must be another issue with your code. In your while() loop, do a var_dump($auctionRow); - what is in your array?
I tried echo $auctionRow['question_body'] then var_dump($auctionRow) in the while loop. Didn't work either.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.