Im having a problem incrementing a counter in one of my while loops basically i just want to alternate between two image links that were fetched in my database but my counter wo
$i = 0;
while($i<5) {
$alternateVal = $i%2==0 ? "type1" : "type2";
echo $alternateVal;
$i++;
}
Above is an example to overview alternate values.
Initialize $i outside the loop.
$i = 0;
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$img_link = $row['Image'];
$img_link_alt = $row['Image_alt'];
echo '<div class="col-xs-6 col-sm-3 placeholder">';
$img = ( $i % 2 == 0 ) ? $img_link : $img_link_alt;
echo $i;
//'?' . date("h:i:sa").'
echo '<img style="height:200px; border-radius:0%; width:300px;" src="screenshots/'. $img . '">';
echo '<h4>Screenshot</h4><span class="text-muted">Updated Screenshot of the Botting session: <b>' . $row['script_name'] .' </b></span>';
echo '</div>';
$i++;
}
Put the $i
variable outside the while
block, like this:
$i = 0;
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$img_link = $row['Image'];
$img_link_alt = $row['Image_alt'];
echo '<div class="col-xs-6 col-sm-3 placeholder">';
$img = ( $i % 2 == 0 ) ? $img_link : $img_link_alt;
echo $i;
//'?' . date("h:i:sa").'
echo '<img style="height:200px; border-radius:0%; width:300px;" src="screenshots/'. $img . '">';
echo '<h4>Screenshot</h4><span class="text-muted">Updated Screenshot of the Botting session: <b>' . $row['script_name'] .' </b></span>';
echo '</div>';
$i++;
}
You have to reset $i outside the loop:
$i = 0;
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$img_link = $row['Image'];
$img_link_alt = $row['Image_alt'];
echo '<div class="col-xs-6 col-sm-3 placeholder">';
$img = ( $i % 2 == 0 ) ? $img_link : $img_link_alt;
echo $i;
//'?' . date("h:i:sa").'
echo '<img style="height:200px; border-radius:0%; width:300px;" src="screenshots/'. $img . '">';
echo '<h4>Screenshot</h4><span class="text-muted">Updated Screenshot of the Botting session: <b>' . $row['script_name'] .' </b></span>';
echo '</div>';
$i++;
}
move the
$i
initialization:
$i=0
outside of the while loop and it worked. you every time renizialize the
$i
variable in your while loop,and your counter don't increase, fix it. An alternative is use the rows counter, like that example:
$count = $db->query("SELECT COUNT(id) FROM users")->fetchColumn();
echo $count; //Returns number of rows
like in that answer