简体   繁体   中英

printing 2 columns in a table while in for loop

I am trying to print results from a mysql query in a table that will be in 2 columns. to do this through my for loop i did the following:

    $num = 1;
            while($r = $qry->fetch())
            {
                    if (!fmod($num,2)) echo '<tr>';
                    echo "<td>" . $num . "</td>";
                    if (!fmod($num,2)) echo '</tr>';
                    $num++;
           }

however, each row is getting its own row in the table. even though $num is printed and shows 1,2,3,4 and so on. what am i missing?

You got it almost right, but each iteration needs to EITHER display a <tr> OR an </tr> so:

https://eval.in/93455

$num = 1;
        while($num < 11)
        {
                if (fmod($num,2)) echo '<tr>';
                echo "<td>" . $num . "</td>";
                if (!fmod($num,2)) echo '</tr>';
                $num++;
       }

Note I altered your while condition for test purposes

I would recommend that you do this instead. It creates a table, and lists column1 and column2 for each row.

    $result
        ?>
         <table>
          <tr>
           <th> Data for column 1</th>
          </tr>
         <tr>
        <?
        while($row = mysqli_fetch_assoc($result))
        {

          echo "<td>".$row['dataforcolumn1']."</td>";
        }
    ?>
</tr>
    </table>

I would simplify it with doing this:

$num = 1;
            while($r = $qry->fetch_array())
            {
                    if(fmod($num,2)) echo "</tr>\n";
                    echo "<td>" . $r['columnName'] . "</td>\n";
                    if(!fmod($num,2)) echo '</tr>';
                    $num++;
           }

Mainly, this is changing the fmod command to be divisible by 2 to end the tag as you want it to add that after there are two tags added (meaning it SHOULD be divisible by 2).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM