Kyle
Kyle

Reputation: 1183

Using an If statement in a While loop PHP

Trying to test which row the loop is on and if it's greater than or equal to six, plug the $TESTIMAGE variable into the span element for the next iteration.

When I run the code, it plugs the variable into everything following the first row.

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";
}   



}

Upvotes: 1

Views: 2550

Answers (5)

Matthew Smith
Matthew Smith

Reputation: 6255

The call to mysql_num_rows($result) always returns the same number. You want to increment an index on each iteration instead:

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

Upvotes: 0

adeneo
adeneo

Reputation: 318182

$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 />
    ";
}​

Upvotes: 0

MAXIM
MAXIM

Reputation: 1221

try it like this:

$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++;

}

Upvotes: 0

Mike Brant
Mike Brant

Reputation: 71384

That is because mysql_num_rows() will return the same exact value for each iteration of the loop, as the number of rows in the result change will not change.

You would need to implement a counter to do what you are wanting to do.

Upvotes: 0

Justin McDonald
Justin McDonald

Reputation: 2166

use an increasing index:

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

Upvotes: 2

Related Questions