You wrote:
Expected is defined $row_wohn_by with 0
Looking at your query (SELECT priv_land, COUNT(*) AS count FROM members
), this can only be the case when there are no rows with priv_land = 'by'
. So within your while
-loop just after your query, that variable never got set.
Solution: initialize all variables with value 0 and overwrite those with the results from your query:
foreach($states as $privLand) {
${'row_wohn_' . $privLand} = 0;
${'row_wohn_per_' . $privLand} = 0;
}
$query_wohn = mysqli_query($conn, "SELECT `priv_land`, COUNT(*) AS `count` FROM `members` WHERE `priv_land` !=0 GROUP BY `priv_land`");
while ($item_wohn = $query_wohn->fetch_assoc()) {
${'row_wohn_'.$states[$item_wohn['priv_land']]} = $item_wohn['count'];
${'row_wohn_per_'.$states[$item_wohn['priv_land']]} = number_format((($item_wohn['count'] / $total_wohn)*100), 2, ',', ' '); // calulate in %
}
For bonus points, rewriting everything to an array-notaition makes life a lot easier (example for only $row_wohn_*
):
// Initialize all keys with value 0
$row_wohn = array_fill_keys($states, 0);
$query_wohn = mysqli_query($conn, "SELECT `priv_land`, COUNT(*) AS `count` FROM `members` WHERE `priv_land` !=0 GROUP BY `priv_land`");
while ($item_wohn = $query_wohn->fetch_assoc()) {
$row_wohn[ $states[$item_wohn['priv_land']] ] = $item_wohn['count'];
}
$row_wohn_all = $total_wohn - array_sum( $row_whon );