Reputation: 11
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.
Upvotes: 0
Views: 51
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
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