dongtan8122 2014-10-23 09:01
浏览 40
已采纳

PHP while循环回显重复

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?

  • 写回答

1条回答 默认 最新

  • dongtuo6562 2014-10-23 09:25
    关注

    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 !

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测