mwangii
mwangii

Reputation: 11

How to populate array data into a HTML table

I am trying to populate an array into a HTML table, but I keep getting Notice: Undefined offset

What am I doing wrong?

<?php
class Invoices{
    public $database;
    public $exec;

    public function __construct(){
        $this->database = new Dbase();
    }

    public function show(){
        $query="SELECT * FROM invoices;";
        $this->exec=$this->database->fetch($this->database->run($query));
        echo '<table class="table table-striped table-bordered"><thead>
                <tr>
                <th>ID</th>
                <th>Customer ID</th>
                <th>Products</th>
                <th>Total</th>
                <th>Status</th>
                <th></th>
                </tr>
                </thead>';
        for ($i=0; $i<count($this->exec, 0); $i++){
            echo '<tr>';
            for ($j=0; $j<5; $j++){
                echo '<td>'.$this->exec[$i][$j].'</td>';
            }
            echo '</tr>';
        }
        echo '</table>';
    }
}
?>

Below are the results of var_dump() on the $exec array.

var dump

Upvotes: 0

Views: 51

Answers (2)

Don&#39;t Panic
Don&#39;t Panic

Reputation: 41820

If you use foreach loops, you won't need to worry about incorrect indexes.

In my opinion, a for loop is usually better for doing something a specific number of times,and if you're just iterating over every item in an array, foreach is usually more straightforward.

foreach ($this->exec as $invoice)
{
    echo '<tr>';
    foreach ($invoice as $column)
    {
        echo '<td>'.$column.'</td>';
    }
    echo '</tr>';
}

Upvotes: 2

I wrestled a bear once.
I wrestled a bear once.

Reputation: 23409

Hardcoding array lengths is a big no no

    foreach($this->exec[$i]as $j)
    {
        echo '<td>'.$this->exec[$i][$j].'</td>';
    }

But if you must harcode the count, make sure you get it right. according to your markup it looks like you;re expecting 6 elements ,not 5.

Upvotes: 0

Related Questions