<?php
  function stats()
  {
    if(!$db = mysqli_connect("localhost", "php", "test")){
      //echo("Problem z połączeniem z bazą danych");
      return;
    }
    if(!mysqli_select_db($db, "testphp")){
      //echo("Problem z wyborem bazy testphp");
      mysqli_close($db);
      return;
    }

    $arr_systemy = array('windows', 'linux');
    $arr_systemy_res = array();
    $arr_browsers = array('chrome', 'firefox', 'msie', 'opera');
    $arr_browsers_res = array();

    foreach($arr_systemy as $val){
      $query = "SELECT COUNT(*) FROM Stats WHERE agent LIKE '%$val%'";

      if(!$result = mysqli_query($db, $query)){
        //echo("Problem z bazą danych: odrzucone zapytanie");
        $arr_systemy_res[] = 0;
      }
      else{
        if(!$row = mysqli_fetch_row($result)){
          $arr_systemy_res[] = 0;
        }
        else{
          $arr_systemy_res[] = $row[0];
        }
      }
    }

    foreach($arr_browsers as $val){
      $query = "SELECT COUNT(*) FROM Stats WHERE agent LIKE '%$val%'";
      if(!$result = mysqli_query($db, $query)){
        //echo("Problem z baz&plusmn; danych: odrzucone zapytanie");
        $arr_browsers_res[] = 0;
      }
      else{
        if(!$row = mysqli_fetch_row($result)){
          $arr_browsers_res[] = 0;
        }
        else{
          $arr_browsers_res[] = $row[0];
        }
      }
    }

    mysqli_close($db);
    
    $count = 0;
    foreach($arr_systemy_res as $key => $val){
      echo $arr_systemy[$key] . ": " . $val . "<br>";
      $count += $val;
    }

    echo "Razem $count <br><br>";
    
    $count = 0;
    foreach($arr_browsers_res as $key => $val){
      echo $arr_browsers[$key] . ": " . $val . "<br>";
      $count += $val;
    }

    echo "Razem $count";
  }
?>

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Moja strona WWW</title>
  </head>
  <body>
    <div>
    <?php
      echo stats();
    ?>
    </div>
  </body>
</html>
