626
626

Reputation: 1159

Custom Table using SQL query and php

I am trying to create a table from a sql query but I need to only have 3 results per table row.

I have a list of about 47 names so I have no problem printing them on a new line but how would I go about creating a table where the while loop would print a table row then print 3 table data cells with the query then create a new row for the next 3 values?

Exa:

result_1 | result_2 | result_3
result_4 | result_5 | result_6
result_7 | result_8 | result_9

Current While Loop:

while($row = mysql_fetch_assoc($result)) {

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


        }

Database Structure:

id | name
1 | result_1
2 | result_2
3 | result_3
4 | result_4

Thanks in advance!

Upvotes: 1

Views: 906

Answers (2)

Dragos Giurca
Dragos Giurca

Reputation: 16

Try looping through the results using a for loop, then compare the remainder of dividing the iterator by 3, using the modulus operator.

echo "<tr>";
for($i = 0; $i<mysql_num_rows($result); $i++) {
  if($i%3==0) {
    echo "</tr><tr>";
  }
  $row = mysql_fetch_assoc($result)
  echo "<td><input type='checkbox'> ".$row['name']."</td>";
}
echo "</tr>";

Upvotes: 0

ThreeLLMsInATrenchcoat
ThreeLLMsInATrenchcoat

Reputation: 519

You can use the modulus operator (%) to check if you're ready for a new line.

    $number_of_names = count($names);
    $number_of_columns = 3; //you can change this at any point

    echo "<table><tr>";

    for($i=0;$ i<$number_of_names; $i++){
        echo "<td>" . $names[$i] . "</td>";

        if ($i % $number_of_columns == ($number_of_columns - 1) && $i<$number_of_names-1){
            echo "</tr><tr>";
        }
     }

     echo "</tr></table>";

Upvotes: 1

Related Questions