0

I need some help with some methodology

I have a SQL statement that fetches results from a questions 'header table'.

while() the data is being fetched I'm running another SQL statement that pulls comments from a 'sub table' according to the id fetched from the questions table.

When I echo all together, question number 1's comments show fine, all the comments related to the question are showing fine.

The issue is when question number 2's comments are echoed, comments from question number 1 show up (duplicated).

I just can't figure out where I'm going wrong.

Here's a simplified version of what my code looks like just to show the methodology:

$comment_list = ""; // to display comments
$GET_QUESTIONS = $DBH->prepare("SELECT ...");
// parameters are bound here using $GET_STATEMENTS->bindParam();

while($row = $GET_QUESTIONS->fetch(PDO::FETCH_ASSOC)){

    $question_id = $row['id'];
    $question_string = $row['string'];

    // NOW I PULL THE COMMENTS
    $GET_COMMENTS = $DBH->prepare("SELECT ...");
    // parameters are bound here using $GET_COMMENTS->bindParam();

    while($row = $GET_COMMENTS->fetch(PDO::FETCH_ASSOC)){

        $comment_id = $row['id'];
        $comment_string = $row['string'];

        $comment_list .= "
            <p>" .$comment_string. "</p>
        ";

    }

    echo "
        <h1>" .$question_string. "</h1>
        " .$comment_list. "

    ";

}

Why are the duplicates happening when echoing the second question?

2
  • 3
    You've to reset the $comment_list variable before the second while loop. Set it as $comment_list = null ; just before the second while loop. Commented Oct 23, 2014 at 9:06
  • 1
    @DareScorp, thanks, that solved it! Please post as an answer so I can accept Commented Oct 23, 2014 at 9:11

1 Answer 1

2

You've to reset the $comment_list variable before the second while loop. Set it as

$comment_list = null ; 

Just before the second while loop. That's all !

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

Comments

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.