user2376009
user2376009

Reputation: 31

Results are not showing correct in table

I am completely new in PHP so this question might be stupid. I could not find an answer after searching for hours.

I have made a query with a foreach loop but it does not show it right in the table I create. The part from the foreach show all in the field next to the last country.

I have tried to put the on all kind of other places but the result stays the same it does not come in the right column.

$query = "SELECT COUNT(landofbirth) as c, landofbirth FROM dog WHERE landofbirth IS NOT NULL GROUP BY landofbirth ORDER BY c desc LIMIT 1000"; 
$result = mysql_query($query) ;
$values = array();
$pct = array();
$total = 0;

while ($line = mysql_fetch_array($result)) {
    echo "<tr><td>";
    $values[$line[1]] = $line[0];
    $total += $line[0];
    echo "$line[1]</td><td> ";

    echo "$line[0] </td><td>"; }

    foreach($values as $key => $value) {
    $pct[$key] = $value/$total ; 
    $count2 = $pct[$key] * 100;
    $count = number_format($count2, 2);
    echo "$count %"; }
    echo "</td></tr>";

Upvotes: 0

Views: 74

Answers (1)

newfurniturey
newfurniturey

Reputation: 38436

Your code is a bit garbled, perhaps from moving it around one too many times.

I always find it helpful to separate the display items one-by-one, even put them each on individual lines and away from the "calculation" code for better visuals when editing the code.

I'm not exactly sure if this is what you're looking for, but I think this display will be close (and/or easily modifiable):

while ($line = mysql_fetch_array($result)) {
    $values[$line[1]] = $line[0];
    $total += $line[0];
}

foreach($values as $key => $value) {
    $pct[$key] = $value/$total ; 
    $count2 = $pct[$key] * 100;
    $count = number_format($count2, 2);

    echo '<tr>';
        echo '<td>' . $key . '</td>';
        echo '<td>' . $value . '</td>';
        echo '<td>' . $count . '%</td>';
    echo '</tr>';
}

Side Note (not answer specific)
It is recommended that you do not develop with the deprecated mysql extension in PHP. Instead, you should use the alternative and maintained mysqli or PDO extensions. Both are far more secure to use and provide beneficial features such as prepared statements!

Upvotes: 4

Related Questions