Syed Syed - 4 months ago 16
MySQL Question

how to add condition in Nth row of the MySQL database fetching in codeigniter

I am using codeigniter and I am stuck in giving if condition in a database loop:

<?php
foreach ( $gallery as $raw ) {

$g_id = $raw->gallery_id;
$src_z =$raw->zoom_img;
$src_m = $raw->main_img;
$src_t =$raw->thumb_img;
echo "<a href='#' data-zoom-image='".base_url().$src_z."'";
echo "data-image='".base_url().$src_m."' class='active d_block wrapper r_corners tr_all translucent m_bottom_10'>";
echo "<img src='".base_url().$src_t."' alt='' class='r_corners'></a>";

if ( /*row is 4th then add*/ ) {
echo "</li><li>";
}
}
?>


If the row is the 4th then it should add
</li><li>
at the end.

Answer

Simply create a variable (In this case $i) outside the loop, and increment in within the loop (++ before the $i), and then check if it's the 4th iteration (Also the 4th loop):

<?php 
    $i = 0;
    foreach ($gallery as $raw) {
        $g_id = $raw->gallery_id;
        $src_z =$raw->zoom_img;
        $src_m = $raw->main_img;
        $src_t =$raw->thumb_img;
        echo "<a href='#' data-zoom-image='".base_url().$src_z."'"; 
        echo "data-image='".base_url().$src_m."' class='active d_block wrapper r_corners tr_all translucent m_bottom_10'>";
        echo "<img src='".base_url().$src_t."' alt='' class='r_corners'></a>"; 

        if(++$i == 4) //$raw is the 4th iteration
        { 
            echo "</li><li>";
        }

        //For every 4th row, use this:
        // if ( ++$i % 4 == 0 )
    }
?>