Jump to content

Problem with while loop and html output


saynotojava

Recommended Posts

I have currently this code:

echo'<table border="1">';


    while($row = $ret->fetchArray(SQLITE3_ASSOC) ){

      echo '<tr><td>' .$row['Domain'].'</td><td><input type="checkbox" name="a[]" value="n"></td></tr>';


}
echo'</table>';

Which will output query from database and it will show output in that table format.But the problem is, when there is a lot of info pulled of,it look bad as a lot of space in unused then,so

i want to make it every fifth output to show in new line(compared to current where every output goes to new line).Also,output does'nt need to be with tables,i just want to make it look normaly aligned.

Link to comment
https://forums.phpfreaks.com/topic/282828-problem-with-while-loop-and-html-output/
Share on other sites

Try replacing while loop using below code

$i = 1;
echo '<tr>';
while($row = $ret->fetchArray(SQLITE3_ASSOC) )
{
      echo '<td>' .$row['Domain'].'</td><td><input type="checkbox" name="a[]" value="n"></td>';
      if ($i % 5 == 0)
             echo '</tr><tr>';
      $i++;
}
echo '</tr>';
echo'<table border="1">';

$col = 0; // column counter
$max_cols = 5; // how many columns per row

$tresults = 0; // results counter
$max_results = $ret->numRows(); // total number of results
while($row = $ret->fetchArray(SQLITE3_ASSOC)) {

if($col == 0) // if col is 0, start new table row
echo '<tr>';

echo '<td>' .$row['Domain'].'</td><td><input type="checkbox" name="a[]" value="n"></td>'; // echo a column

$col++; // increment column counter
$tresults++; // increment results counter

if($col == $max_cols) { // if col equals to max columns
echo '</tr>'; // end table row
$col = 0; // reset column counter
}
elseif($tresults == $max_results && $col < $max_cols) // if we have processed all results, but $col is still less than max number of columns
echo str_repeat('<td></td>', $max_cols - $col) . '</tr>'; // then clean up table, output empty columns and end table row
}
echo'</table>';

 

Try replacing while loop using below code

$i = 1;
echo '<tr>';
while($row = $ret->fetchArray(SQLITE3_ASSOC) )
{
      echo '<td>' .$row['Domain'].'</td><td><input type="checkbox" name="a[]" value="n"></td>';
      if ($i % 5 == 0)
             echo '</tr><tr>';
      $i++;
}
echo '</tr>';

Works as charm,thanks.I know it trick is in increment and if but didn't know how exactly to put it.

In case you're interested, array_chuck() could be used to break the column groups. This doesn't require a counter. For an example which closely relates to your question, check out http://www.cyberscorpion.com/2013-08/build-html-tables-dynamically-with-php-part-2-simplify-with-array_chunk/

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.