在While循环PHP中使用If语句

时间:2012-12-11 00:38:23

标签: php if-statement while-loop

尝试测试循环所在的行以及它是否大于或等于6,将$ TESTIMAGE变量插入span元素以进行下一次迭代。

当我运行代码时,它会将变量插入到第一行之后的所有内容中。

While($row = mysql_fetch_array($result))

{

    //assign variables
    $title = $row['title'];
    $url = $row['location'];
    $image = "/waves/files/images/games/$title.png";

    echo "
            <span class='dropt'>

                <a href=$url>$title</a>

                        <span class='$TESTIMAGE'>
                            <img src='$image'>
                        </span>

            </span>
            <br />
    ";



//Test to see which row we're on -- adjust image position
If (mysql_num_rows($result) >= 6)
{
$TESTIMAGE = "image_display_up";
}   



}

5 个答案:

答案 0 :(得分:2)

使用增加的索引:

$i = 0;
while($row = mysql_fetch_array($result)){
    $i += 1;
}

答案 1 :(得分:0)

这是因为mysql_num_rows()将为循环的每次迭代返回相同的确切值,因为结果更改中的行数不会改变。

你需要实施一个计数器来做你想做的事。

答案 2 :(得分:0)

尝试这样:

$i = 1;

While($row = mysql_fetch_array($result)) {
    if(!($i%6)) {  // will enter here on the 6th try.

    //assign variables
    $title = $row['title'];
    $url = $row['location'];
    $image = "/waves/files/images/games/$title.png";

        echo "
        <span class='dropt'>

            <a href=$url>$title</a>

                    <span class='$TESTIMAGE'>
                        <img src='$image'>
                    </span>

            </span>
            <br />
       ";
  }
  if($i!=6)  // this way it remains on 6
     $i++;

}

答案 3 :(得分:0)

$i=0;
While($row = mysql_fetch_array($result)) {
    //assign variables
    $title = $row['title'];
    $url = $row['location'];
    $image = "/waves/files/images/games/$title.png";
    $TESTIMAGE = ($i++ >= 6) ? "image_display_up" : "";

    echo "
            <span class='dropt'>
                <a href=$url>$title</a>
                        <span class='$TESTIMAGE'>
                            <img src='$image'>
                        </span>
            </span>
            <br />
    ";
}​

答案 4 :(得分:0)

对mysql_num_rows($ result)的调用始终返回相同的数字。您希望在每次迭代时增加索引:

$idx = 0
while (blah) {
    if ($idx >= 6)
    {
        $TESTIMAGE = "image_display_up";
    }   
    $idx += 1
}