Join the Stack Overflow Community
Stack Overflow is a community of 6.5 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

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 vardump on the $exec array.

var dump

share|improve this question
1  
your $j is not a numeric key, its: id, customer_id etc – nogad 3 hours ago
1  
I think using a foreach loop instead would simplify things. – Don't Panic 3 hours ago

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>';
}
share|improve this answer

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.

share|improve this answer
    
$j=0; what are you talking about? – I wrestled a bear once. 3 hours ago
    
oh, you're assuming the db returns an associative array but you don't know that. – I wrestled a bear once. 3 hours ago
    
i stand corrected. fixed the answer. – I wrestled a bear once. 3 hours ago

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.