Search code examples
htmlxhtmlhtml4

How to allow only 4 cells per row in a table in HTML?


I'd like to know if there's a way to allow only 4 cells per row in HTML .. only 4 allowed in a table , if it's more than 4 tds , then another row gets created ..

How could I control that in HTML ?


Solution

  • No, you don't seem to understand what you're asking. You CANNOT do this automatically with only html. Your question pertains to both Html and Php.

    Here's a quick n nasty job:

    $pdo = new PDO("mysql:host=$host;dbname=$dbName", $userName, $pwd);
    
    $query = $pdo->prepare('select name from products order by id asc');
    $query->execute();
    
    echo '<table>';
    echo '<tbody>';
    $numCellsInRow = 0;
    while ($curRow = $query->fetch())
    {
        if ($numCellsInRow == 4)
        {
            printf("</tr>");
            $numCellsInRow = 0;
        }
        if ($numCellsInRow == 0)
        {
            printf("<tr>");
        }
        printf("<td>%s</td>", $curRow[0]);
    
        $numCellsInRow++;
    }
    echo '</tbody>';
    echo '</table>';
    

    Result

    <table>
      <tbody>
        <tr>
          <td>1" tweeter</td>
          <td>6" sub</td>
          <td>Sony Headphones</td>
          <td>Magnifier</td>
        </tr>
        <tr>
          <td>Red Led</td>
          <td>Blue LED</td>
          <td>7 segment LED</td>
          <td>Lalique stained glass</td>
        </tr>
        <tr>
          <td>LED downlight</td>
          <td>BiPole light-switch</td>
          <td>DC, 10amp</td>
          <td>Monster Cable</td>
        </tr>
        <tr>
          <td>Sata 2.0 Cable</td>
          <td>Speaker Wire</td>
          <td>USB 2.0 A to B Cable</td>
        </tr>
      </tbody>
    </table>