Garg Garg - 2 months ago 7
MySQL Question

Each second item from mysql in different div box

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>

Answer

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