2012-04-12 86 views
0

我正在为我的网站做一个ajax评论系统,我正在查询我的数据库的任何意见与某个领域。然后查看返回的结果数是否大于3,或者小于/等于3(我有3的特定原因)。如果它大于3,我设置一个变量= 3,但是如果它小于/等于3,我将该变量设置为返回的行数(mysql_num_rows())。然后我在循环之前回显一些文本,然后回显循环中的内容,然后在循环之后回显更多内容。出于某种原因,我的for循环运行超过了给定的时间。非常奇怪的是,在转向下一个评论并回应3次之前,它回应了同样的评论3次。在for循环之后,我总共有9条评论。这种情况不适用于我的设计,因为我只能放3个评论,我将它们放在哪里。我的for循环嵌套了几个时间段,因为我需要多次查询才能根据我发送给php的信息获取我需要的信息(具体原因也是这样)。另一件事,PHP只回应评论9次,只有返回结果的数量是大于 3如果小于3,它可以正常工作。我已经完成了这个代码50次,但是我找不到任何东西。也许你们可以。继承人的代码我使用:PHP for循环运行超过它应该


   $comments = mysql_query("SELECT * FROM comments WHERE profid = '".$row['id']."'"); 
       $numComments = mysql_num_rows($comments); 
       $totalCommComments = 0; 
       if ($numComments > 0) { 
        if (mysql_num_rows($comments) > 3) { 
         $totalCommComments = 3; 
         echo ' 
     <div class="comments"> 
      <div class="commContainer"> 
       <ul class="'.$totalCommComments.'Comm">'; 
         while ($get1 = mysql_fetch_array($comments)) { 
         for ($l = 1;$l<$totalCommComments;$l++) { 
          echo 'STUFF IS ECHOED HERE'; 
         } 
         } 
         echo ' 
       </ul> 
      </div> 
     </div>'; 

我知道变量$totalCommComments设置为3,因为我可以看到在<ul>类。

PS。这不是完整的代码,只有相关的代码。其他一切都在查询不同的数据库以获取进行此查询所需的其他信息。


谢谢你这么多

+0

其余的代码是 – 2012-04-12 15:55:53

+0

'$ totalCommComments'和'$ numComments'有什么区别? – Josh 2012-04-12 15:57:14

回答

4
$comments = mysql_query("SELECT * FROM comments WHERE profid = {$row['id']}"); 
$numComments = mysql_num_rows($comments); 
if ($numComments > 0) { ?> 
    <div class="comments"> 
     <div class="commContainer"> 
      <ul class="shortComments"> 
       <?php $i = 0; 
       while ($i++ < 3 && $get1 = mysql_fetch_assoc($comments)) { ?> 
        <li class='comment'><?=$get1['comment']?></li> 
       <?php } ?> 
      </ul> 
     </div> 
    </div> 
<?php } ?> 

尝试。你有大量的冗余代码有

有很多不同的方式,我可以继续编辑这个,如果你让我们知道你正在尝试做的,我可以更新这个代码

+0

我不确定,但我认为* OP要限制显示的评论数量。 – Josh 2012-04-12 16:00:37

+1

@Josh,目前只限于三条评论 – Ascherer 2012-04-12 16:01:00

+2

+1只需要刷新。我的错。说实话,如果这些注释不用于其他地方,OP应该在查询中使用“LIMIT”子句。 – Josh 2012-04-12 16:02:16

1

摆脱在while语句中进行,

while ($get1 = mysql_fetch_array($comments)) { 
        for ($l = 1;$l<$totalCommComments;$l++) { 
         echo 'STUFF IS ECHOED HERE'; 
        } 
        } 

应该只是

while ($get1 = mysql_fetch_array($comments)) { 

         echo $get1['whatever']; 

        } 

这同时将循环中的所有自动意见,为您添加是什么trippling返回的结果

0

$ numComments是注释的数量,$ totalCommComments可能是0或3.您有一段时间有$ numComments迭代,并且每次迭代时您有一次迭代0或3次。这意味着你将有$ numComments * $ totalCommComments迭代,这是非常正常的。

在我看来,你应该有一个单一的循环,你的索引和循环条件应该纠正。