Question

I am getting tables from database and display them. For some database tables there are 4 columns to display, others have 5 or more columns to display. I can get everything to work but only in a hardcoded way - meaning I currently have to create the tabledata-tags foreach table separately. How can I make this dynamic?

I assume by somehow doing the foreach inside the controller and then send it to the View but I can't get it to work. Can anybody give me hint please in how to make the table reusable for every table (irrespective of how many columns a table has).

Controller

$data['rows'] = $this->main_categories_model->get();
$this->load->view('admin/admin_layout', $data);

View

<?php foreach($rows as $row) : ?>
    <tr>
        <td><?php echo $row->id; ?></td>
        <td><img src="<?php echo $row->mainpic; ?>"></td>
        <td><?php echo $row->name_en; ?></td>
        <td><?php echo $row->name_de; ?></td>
    </tr>
<?php endforeach; ?>
Was it helpful?

Solution

The following will help you.

    <?php foreach($rows as $row) : ?>
        <tr>
            <?php foreach($row as $key=>$value) : ?>        
                    <td><?php echo $row->$key; ?></td>
            <?php endforeach; ?>
        </tr>
    <?php endforeach; ?>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top