Ivan Ivan - 2 months ago 13
MySQL Question

Showing different titles in table TR on certain rows with php

I have values in database which I show in table on page. They are always 10. I want to show different

Name
when the loop hit 9th and 10th rows. I've tried this which doesn't seems to be the correct way

while ($row=$result_rates->fetch_all(MYSQLI_ASSOC)) {
$counter = 0;
foreach ($row as $r){
if($counter<9)
{
echo '<tr>
<td>'.$r['number'].'</td>
<td>$ <span>'.$r['price'].'</span></td>
</tr>';
}
else {

echo '<tr>
<td>Number 9</td>
<td>$ <span>'.$r['price'].'</span></td>
</tr>
<tr>
<td>Number 10</td>
<td>$ <span>'.$r['price'].'</span></td>
</tr>';
}
}
}


Is this possible with tables and how?

Answer Source

You need to do it like below:-

$counter = 1;
foreach ($row as $r){

    $html = ($counter==9 || $counter==10)?  '<tr><td>Number '.$counter.'</td><td>$ <span>'.$r['price'].'</span></td></tr>'  : '<tr><td>'.$r['number'].'</td><td>$ <span>'.$r['price'].'</span></td></tr>'
    echo $html;
    $counter++; //you forgot it
}

Or you can try this:-

$counter = 1;
foreach ($row as $r){

    $html = ($counter>8)?  '<tr><td>Number '.$counter.'</td><td>$ <span>'.$r['price'].'</span></td></tr>'  : '<tr><td>'.$r['number'].'</td><td>$ <span>'.$r['price'].'</span></td></tr>'
    echo $html;
    $counter++; //you forgot it
}

Note:- while is not needed because $row have all records in it already