Reputation: 3375
I have 2 different html div boxes and I want to populate them with data from my database like div 1 - div 2 - div 1 - div 2
. For this I've tried with counter and make each second box to be div 2
but seems like doesn't work.. I've got doubled of results.
Here is what I have tried so far
$result = $pdo->prepare("SELECT * from projects");
$result->execute();
$counter=0;
for($i=0; $row = $result->fetch(); $i++)
{
$counter++;
echo '
<div class="itemm w_30">
// load data
</div>';
if($counter%2==0)
{
echo '<div class="itemm w_40">
// load data
</div> ';
}
}
So on the page I want to see data like
<div class="itemm w_30">
// data
</div>
<div class="itemm w_40">
// data
</div>
<div class="itemm w_30">
// data
</div>
<div class="itemm w_40">
// data
</div>
Upvotes: 0
Views: 77
Reputation: 94642
Simply use a ternary operator to set the required class name like this
$result = $pdo->prepare("SELECT * from projects");
$result->execute();
$onLeft = true;
while( $row = $result->fetch() ) {
$class = $onLeft ? "itemm w_30" : "itemm w_40";
echo "<div class='$class'>";
// Show data
echo '</div>';
$onLeft = !$onLeft;
}
Upvotes: 1
Reputation: 6628
Just use %
for loop, no need to use counter
variable.
for($i=0; $row = $result->fetch(); $i++)
{
if($i%2==0)
{
echo '<div class="itemm w_40">
// load data
</div> ';
}
else
{
echo '<div class="itemm w_30">
// load data
</div>';
}
}
Upvotes: 1
Reputation: 588
just write first echo on else
$result = $pdo->prepare("SELECT * from projects");
$result->execute();
$counter=0;
for($i=0; $row = $result->fetch(); $i++)
{
$counter++;
if($counter%2==0)
{
echo '<div class="itemm w_40">
// load data
</div> ';
} else{
echo '
<div class="itemm w_30">
// load data
</div>';
}
}
Upvotes: 2
Reputation: 4220
You need to put all of your divs in IF ELSE block
if($counter%2==0)
{
echo '<div class="itemm w_40">
// load data
</div> ';
} else {
echo '
<div class="itemm w_30">
// load data
</div>';
}
Upvotes: 4