php - Undefined variable if variable get result from array -


i have defined array. if 1 column (e.g. bayern 'by') empty, not receive variable $row_wohn_by , after in result is: notice: undefined variable: row_wohn_by

simply erase not solution operate. expected defined $row_wohn_by 0 (zero) number.

here code:

$states = array(     'baden-württemberg' => 'bw',     'bayern' => 'by',     'berlin' => 'be',     'thüringen' => 'th'     );      $numb_rows = mysqli_query($conn, 'select count(*)                                         members                                         priv_staat = "deutschland"                                         ');         $numb_row = mysqli_fetch_array($numb_rows);         $total_wohn = $numb_row[0];      $query_wohn = mysqli_query($conn, "select `priv_land`, count(*) `count` `members` `priv_land` !=0 group `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 %     }      $row_wohn_all = $total_wohn-($row_wohn_bw + $row_wohn_by + $row_wohn_be + $row_wohn_th);     $row_wohn_per_all = number_format((($row_wohn_all / $total_wohn)*100), 2, ',', ' ');  // calulate in % 

thanks help.

you wrote:

expected defined $row_wohn_by 0

looking @ query (select priv_land, count(*) count members), can case when there no rows priv_land = 'by'. within while-loop after query, variable never got set.

solution: initialize variables value 0 , overwrite results query:

foreach($states $privland) {     ${'row_wohn_' . $privland} = 0;     ${'row_wohn_per_' . $privland} = 0; }  $query_wohn = mysqli_query($conn, "select `priv_land`, count(*) `count` `members` `priv_land` !=0 group `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 array-notaition makes life lot easier (example $row_wohn_*):

// initialize keys value 0 $row_wohn = array_fill_keys($states, 0);  $query_wohn = mysqli_query($conn, "select `priv_land`, count(*) `count` `members` `priv_land` !=0 group `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 ); 

Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -