shibbir ahmed shibbir ahmed - 6 months ago 12
MySQL Question

How to show few columns and then rest of other columns in php while loop?

I am showing all rows from mysql database using following php loop :

<tr>
<?php
$get_status = mysqli_query($link, "SELECT * FROM status ORDER BY status_order ASC");
while($status_result = mysqli_fetch_array($get_status) ) {
$status_name = htmlspecialchars($status_result['status_name']);
$status_order = htmlspecialchars($status_result['status_order']);
echo "<td><input type='checkbox' name='$status_name' value='$status_name'>$status_name</td>";
}
?>
</tr>


As a result, It's look like that :

enter image description here

But what I want is following :

I want to show only 5 columns and then 5 columns and then remaining one and so on...in php while loop. How can I do this ?

Ben Ben
Answer

Add a variable to keep track of the number, then conditionally make a new row, like so:

<?php

    $get_status =  mysqli_query($link, "SELECT * FROM status ORDER BY status_order ASC");

    $n = 0; //Keep track

    while($status_result = mysqli_fetch_array($get_status) ) {
        $status_name =  htmlspecialchars($status_result['status_name']);
        $status_order =  htmlspecialchars($status_result['status_order']);
        echo "<td><input type='checkbox' name='$status_name' value='$status_name'>$status_name</td>";

        $n++; //Increase $n
        if($n%5===0) echo "</tr><tr>"; //Make a new row every 5 iterations of loop
    }