0

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

2
  • 1
    your $j is not a numeric key, its: id, customer_id etc Commented Jan 9, 2017 at 20:51
  • 1
    I think using a foreach loop instead would simplify things. Commented Jan 9, 2017 at 20:54

2 Answers 2

2

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>';
}
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.