我正在为我的网站制作一个ajax评论系统,我正在查询我的数据库以查找某个字段的任何评论。然后我查看返回结果的数量是否大于3,或者小于/等于3(我有一个特定的原因为3)。如果它大于3,我设置变量= 3但是如果它小于/等于3,我将变量设置为等于返回的行数(mysql_num_rows()
)。然后我在循环之前回显一些文本,然后我回显循环中的东西,然后在循环后我回显更多的东西。出于某种原因,我的for循环运行超过给定的时间。非常奇怪的是,在进入下一个评论并回复3次之前,它正在回复相同的评论3次。在for循环之后,我总共有9条评论。这不适用于我的设计,因为我只能在我放置它们的地方放置3条评论。我的for循环嵌套在几个whiles中因为我需要多次查询以根据我发送给php的信息获取我需要的信息(具体原因也是如此)。另一件事,只有当返回结果的数量大于时,PHP才会回复9次评论。如果它小于3,则工作正常。我已经超过了这段代码50次,但我可以'找不到任何东西。也许你们可以。继承我正在使用的代码:
$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 :(得分: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 } ?>
试试看。你有很多冗余代码
我可以通过很多不同的方式继续编辑它,如果你让我们知道你想要做什么,我可以更新这段代码
答案 1 :(得分:1)
摆脱while语句中的for。,
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'];
}
这会自动循环所有评论,而你正在添加的是挽回返回结果的内容
答案 2 :(得分:0)
$ numComments是注释的数量,$ totalCommComments可能是0或3.您有一段时间具有$ numComments迭代,并且对于每次迭代,您有一个0或3次迭代的for。这意味着你将有$ numComments * $ totalCommComments迭代,这是完全正常的。
在我看来,你应该有一个循环,你的索引和循环条件应该被纠正。