'Calculate sum and percentage from MySQL with PHP
I need to calculate the sum of missing hours at an internship and then display said sum in percentage. For example: in this case, the internship has 400 hours and somebody was missing 2 times for 5 hours (sum would be 10), so the percentage would display 2,5.
| Sum | Percentage |
|---|---|
| 10 | 2,5% |
Right now, I only have how to calculate and display the sum, but don't know how to show the percentage of said sum. Here is the PHP code I have so far:
$sql = "SELECT SUM(`fehlzeit`) as 'summe' FROM fehlzeiten WHERE `praktikumsartkuerzel`= 'AP' ";
$result = $conn-> query($sql);
if ($result-> num_rows > 0) {
while ($row = $result-> fetch_assoc()) {
echo "<tr><td>". $row["summe"] ."</td></tr>";
}
echo "</table>";
}
else {
echo "0 result";
}
$conn-> close();
This is the code I tried, but it didn't work:
$sql = "SELECT SUM(`fehlzeit`) as 'summe' FROM fehlzeiten WHERE `praktikumsartkuerzel`= 'AP' ";
$result = $conn-> query($sql);
$allowed = 400;
if ($result-> num_rows > 0) {
while ($row = $result-> fetch_assoc()) {
echo "<tr><td>". $row["summe"] ."</td></tr>";
}
echo "</table>";
}
else {
echo "0 result";
}
$procent = $result / $allowed;
echo $procent;
$conn-> close();
For non-German speakers: fehlzeit means absenteeism, praktikumsartkuerzel means Type of internship abbreviation, summe means sum.
Thank you for the help in advance.
Solution 1:[1]
If you want your percent to appear in your HTML table, you should replace this
echo "<tr><td>". $row["summe"] ."</td></tr>";
with this
echo "<tr><td>". $row["summe"] ."</td><td>". $row["summe"] / $allowed ."</td> </tr>";
putting two <td> ... </td> columns in the row.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | O. Jones |
