1

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!

2
  • have you considered using nested for/while loops as you iterate through your query result to display your table? It would be helpful if you could post more code/db structure and other things that you have tried so far. Commented Mar 25, 2014 at 20:44
  • I updated the post with while loop code and database structure. Thanks Commented Mar 25, 2014 at 20:53

2 Answers 2

1

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>";
Sign up to request clarification or add additional context in comments.

Comments

0

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>";

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.