<?php
  function writeData($db)
  {  
    $time = time();
    $addr = $_SERVER['REMOTE_ADDR'];
    if(isset($_SERVER['HTTP_USER_AGENT'])){
      $agent = mysqli_real_escape_string($db, $_SERVER['HTTP_USER_AGENT']);
    }
    else{
      $agent = "Nieznany";
    }

    $query = "INSERT INTO stats (time, addr, agent) VALUES(";
    $query .= "'$time', '$addr', '$agent')";

    if(!$result = mysqli_query($db, $query)){
      //echo("Problem z bazą danych: odrzucone zapytanie");
      return false;
    }
    else{
      return true;
    }
  }

  function readData($db, $ile, $delimiter)
  {
    $query = "SELECT * FROM stats ORDER BY time DESC LIMIT $ile";
    if(!$result = mysqli_query($db, $query)){
      //echo("Problem z bazą danych: odrzucone zapytanie");
      return false;
    }
    $str = "";
    while(($row = mysqli_fetch_row($result)) != false){
      $str .= date("Y-m-d G:i", $row[0]) . " ";
      $str .= $row[1] . " ";
      $str .= $row[2] . $delimiter;
    }
    return $str;
  }

  function getAndWriteData($ile, $delimiter)
  {
    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;
    }

    $dane = readData($db, $ile, $delimiter);
    writeData($db);

    mysqli_close($db);
    return $dane;
  }
?>

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