Reputation: 1057
I’m trying to style some DIV’s with CSS. What I want to do is change DIV tag class inside MySql loop using PHP.
<?php
$result = $mysqli->query("SELECT * FROM posts ORDER BY id DESC LIMIT 0, 20");
while($row = mysqli_fetch_array($result))
{
?>
<div class=” box id1”><?php echo $row[‘post’];?></div>
<?php } ?>
So I want to change the class box id1 in this order
box id1
box id1
box id2
box id2
box id2
box id2
box id1
box id1
box id2
box id2
box id2
box id2
So on. (2 div tags with the class box id1 then 4 with box id2 looping)
I tried using rand(1, 2); but this making the numbers comes randomly not for the order I want. Any help will be much appreciated. Thanks in advance.
Upvotes: 2
Views: 5744
Reputation: 315
<?php
$result = $mysqli->query("SELECT * FROM posts ORDER BY id DESC LIMIT 0, 20");
$i=1;
$class_str = "";
while($row = mysqli_fetch_array($result))
{
switch($i%6){//deciding for six place
//first two id1
case 1:
case 2:
$class_str="id1";
break;
//four other id2
case 3:
case 4:
case 5:
case 0:
$class_str="id2";
break;
}
$i++;
?>
<div class="box <?php echo $class_str; ?>"><?php echo $row['post'];?></div>
<?php } ?>
Upvotes: 3
Reputation: 450
Basic math operators.
<?php
$result = $mysqli->query("SELECT * FROM posts ORDER BY id DESC LIMIT 0, 20");
$count = 0;
while($row = mysqli_fetch_array($result))
{
?>
<div class=” box id<?php echo min((($count / 2 % 3)+1),2); ?>”><?php echo $row[‘post’];?></div>
<?php
$count++;
} ?>
If you're always sure your posts will be 0-20, you can skip the $count and just use $row["id"].
Upvotes: 0
Reputation: 12665
Make use of InfiniteIterator :
<?php
$infinite = new InfiniteIterator(new ArrayIterator(array(1, 1, 2, 2, 2, 2)));
$infinite->rewind();
$result = $mysqli->query("SELECT * FROM posts ORDER BY id DESC LIMIT 0, 20");
while($row = mysqli_fetch_array($result)) {
$current = $infinite->current();
$infinite->next();
?>
<div class="box id<?php echo $current; ?>"><?php echo $row['post'];?></div>
<?php } ?>
Upvotes: 0
Reputation: 3297
Try using an if loop and a $count variable to determine how many times you've iterated through the SQL results.
<?php
$result = $mysqli->query("SELECT * FROM posts ORDER BY id DESC LIMIT 0, 20");
$count = 1;
while($row = mysqli_fetch_array($result))
{
// If count is <= 2, set boxId = 1
if($count <= 2) {
$boxId = 1;
$count += 1;
// If count is <= 6, set boxId = 2
} elseif($count <= 6) {
$boxId = 2;
$count += 1;
// Once we have two id1 and four id2, reset count to 1
} else {
$count = 1;
}
?>
<div class="box id<?php echo $boxId; ?>"><?php echo $row[‘post’];?></div>
<?php } ?>
Upvotes: 0