phpforeachhtml-table

Stop for loop repeating tables


I have a for loop inserting data into my table, works well.

Problem is each loop I wish for it to start a new row, but it starts a new table. any ideas how to fix this?

 <?php if (isset($records)) : foreach ($records as $row) : ?>

    <div id="mobile-content">
                    <table class="table table-hover">
                        <thead>
                        <tr>
                            <th>Account Name</th>
                            <th>Balance</th>
                            <th>Start Date</th>
                        </tr>
                        </thead>

                        <tbody>
                        <tr>
                            <td><?php echo $row->bank_name; ?></td>
                        </tr>
                        <tr>
                            <td><?php echo $row->bank_balance; ?></td>
                        </tr>
                        <tr>
                            <td><?php echo $row->bank_start_date; ?></td>
                        </tr>
                        </tbody>
                    </table>
                </div>
            <?php endforeach; ?>

Solution

  • You should change the code to loop inside the table body, not in the whole table code:

    <div id="mobile-content">
        <table class="table table-hover">
            <thead>
                <tr>
                    <th>Account Name</th>
                    <th>Balance</th>
                    <th>Start Date</th>
                </tr>
            </thead>
    
            <tbody>
    
            <?php if (isset($records)) : foreach ($records as $row) : ?>
                <tr>
                    <td><?php echo $row->bank_name; ?></td>
                    <td><?php echo $row->bank_balance; ?></td>
                    <td><?php echo $row->bank_start_date; ?></td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    

    Note: I've also remove extra <tr> because you need one row for the three cells.

    I hope that helps :D