[PHP] contatore con sqlite

luigi777

Utente Attivo
14 Feb 2008
1.086
1
38
42
Massa, Italy
Salve, ho trovato questo codice . servirebbe un contatore come questo. ma non capisco perché non funziona.
PHP:
<?php
// logging page hits
$dbfolder = $_SERVER["DOCUMENT_ROOT"]."/data/";
$dbname = $_SERVER["HTTP_HOST"]."_log.sq3";

// check if database file exists first
if(!file_exists($dbfolder.$dbname))
{
 $logdb = new PDO("sqlite:".$dbfolder.$dbname);
 $logdb->exec("CREATE TABLE hits(page VARCHAR(255) PRIMARY KEY, counter INTEGER)");
}
else
{
 $logdb = new PDO("sqlite:".$dbfolder.$dbname);
}

$page = $_SERVER['REQUEST_URI'];

// check if page is already in the hits table
$statement = $logdb->query("SELECT counter FROM hits WHERE page='$page'");
$record = $statement->fetchAll();

// if a record is found
if(sizeof($record) != 0)
{
 $counter = $record[0]['counter']++;
 $logdb->exec("UPDATE hits SET counter=$counter WHERE page='$page'");
 echo "Counter: ".$counter;
}
else
{
 $logdb->exec("INSERT INTO hits(page, counter) VALUES ('$page', 1)");
 echo "Counter: 1";
}

// close connection
$logdb = null;
?>

avete idea?
Grazie mille.
 

macus_adi

Utente Attivo
5 Dic 2017
1.343
91
48
IT/SW
Prova questa classetta...
PHP:
/**
* Created by PHPS.
* User: MADR
* Date: 01/03/2019
* Time: 08:25
*/

class GSql {
   public $conn;
   public $counter_current_page=0;
   public function __construct($path='data',$name='contatore') {
      if(file_exists($path.'/'.$name.'.sqlite')){
         $this->conn = new SQLite3($path.'/'.$name.'.sqlite');
      }else{
         mkdir($path,0777,TRUE);
         touch($path.'/'.$name.'.sqlite');
         $this->conn = new SQLite3($path.'/'.$name.'.sqlite');
      }
   }

   /**
    * Logica per azione da eseguire su record
    * @param string $page Pagina se non esiste viene creato un nuovo record
    * @param bool $fire_action Se agire sui dati o far tornare il valore della query
    *
    * @return $this
    */
   public function check_actions($page,$fire_action=true){
      $res=$this->conn->query('SELECT counter FROM hits WHERE page ="'.$page.'"')->fetchArray(SQLITE3_ASSOC);
      if($fire_action)(empty($res))?$this->create_record($page):$this->increment_page($page);
      else $this->counter_current_page=$res;
      return $this;
   }
   public function create_record($page){
      $this->conn->query('INSERT INTO hits (`page`,`counter`) VALUES ("'.$page.'",1)');
      return $this->check_actions($page,false);
   }

   public function increment_page($page){
      $this->conn->query('UPDATE  hits SET counter = `counter`+1 WHERE `page`= "'.$page.'"');
      return $this->check_actions($page,false);
   }

   public function migrations(){
      $table='create table hits
            (
               page varchar(255) not null,
               counter bigint default 0
            );';
      $index='create unique index hits_page_uindex on hits (page);';
      $this->conn->query($table);
      $this->conn->query($index);
      return $this;
   }
}

//per richiamarla
include_once 'GSql.php';
$conn=new GSql('data','test');
//prima iterazione creiamo la tabella con la migrations
$conn->migrations();

//bisogna caricare i dati...
//basta cambiare la path su check_actions(nome pagina)
$res=$conn->check_actions('test5/aksdnasd/zcx')->counter_current_page;
print_r($res);
 

luigi777

Utente Attivo
14 Feb 2008
1.086
1
38
42
Massa, Italy
ok, ho fatto io uso xampp perché ora voglio usare xampp.. ora mi da questo:
ì
Warning: SQLite3::query(): table hits already exists in D:\xampp\htdocs\GSql.php on line 52

Warning: SQLite3::query(): index hits_page_uindex already exists in D:\xampp\htdocs\GSql.php on line 53
Array ( [counter] => 2 )
 

macus_adi

Utente Attivo
5 Dic 2017
1.343
91
48
IT/SW
Basato su cookies
PHP:
class GSql {
   public $conn;
   public $counter_current_page=0;

   private $cookie_name='my_GSql';

   public $current_cookies='';

   private $store=TRUE;

   public function __construct($path='data',$name='contatore') {
      if(file_exists($path.'/'.$name.'.sqlite')){
         $this->conn = new SQLite3($path.'/'.$name.'.sqlite');
      }else{
         mkdir($path,0777,TRUE);
         touch($path.'/'.$name.'.sqlite');
         $this->conn = new SQLite3($path.'/'.$name.'.sqlite');
      }
   }

   /**
    * Logica per azione da eseguire su record
    * @param string $page Pagina se non esiste viene creato un nuovo record
    * @param bool $fire_action Se agire sui dati o far tornare il valore della query
    *
    * @return $this
    */
   public function check_actions($page,$fire_action=true){
      $this->verify_cookies($page);
      $res=$this->conn->query('SELECT counter FROM hits WHERE page ="'.$page.'"')->fetchArray(SQLITE3_ASSOC);
      if($this->store){
         if($fire_action)(empty($res))?$this->create_record($page):$this->increment_page($page);
         else $this->counter_current_page=$res;
      }else $this->counter_current_page=$res;
      return $this;
   }
   public function create_record($page){
      $this->conn->query('INSERT INTO hits (`page`,`counter`) VALUES ("'.$page.'",1)');
      return $this->check_actions($page,false);
   }

   public function increment_page($page){
      $this->conn->query('UPDATE  hits SET counter = `counter`+1 WHERE `page`= "'.$page.'"');
      return $this->check_actions($page,false);
   }

   public function migrations(){
      $table='create table hits
            (
               page varchar(255) not null,
               counter bigint default 0
            );';
      $index='create unique index hits_page_uindex on hits (page);';
      $this->conn->query($table);
      $this->conn->query($index);
      return $this;
   }


   public function verify_cookies($page){
      if(isset($_COOKIE[$this->cookie_name])){
         $this->current_cookies=$_COOKIE[$this->cookie_name];
         $result=explode(',',$this->current_cookies);
         if(in_array($page,$result))$this->store=FALSE;
         else{
            $result[]=$page;
            $this->store=TRUE;
            $this->current_cookies=join(',',$result);
         }
      }else{
         $this->current_cookies=join(',',[$page]);
         $this->store=TRUE;
      }

      if($this->store){
         setcookie($this->cookie_name,$this->current_cookies);
      }

   }


}
 

macus_adi

Utente Attivo
5 Dic 2017
1.343
91
48
IT/SW
Stampa....
PHP:
include_once 'GSql.php';
$conn=new GSql('data','test');

$res=$conn->check_actions('test1')->counter_current_page;

print_r($res);

// Per fare delle prove fai così
$res=$conn->check_actions(join('/',$_GET))->counter_current_page;

print_r($res);
Inteso che la pagina di test sarà del tipo:
host/test.php?page=ciao&c=true&f=gth
 
Discussioni simili
Autore Titolo Forum Risposte Data
bubino8 [PHP] Contatore Scan QR con redirect PHP 10
Alessandro Le Mura Contatore visite per ogni pagina con MYSQL - PHP PHP 40
T [PHP] [Javascript] Download e contatore PHP 3
M [PHP] Contatore Tempo Server-side PHP 8
M [PHP] contatore record PHP 7
Alessandro Le Mura Contatore php - txt PHP 8
F contatore PHP PHP 12
foki {PHP Script} Contatore Utenti Registrati PHP 17
F Cerco Hosting con VECCHIE versioni di php Hosting 0
Cosina Captcha php PHP 1
S passare un valore da un form a un file .php con metodo post PHP 4
N php msyql PHP 6
N php problemi a visualizzare video PHP 3
A menu a tendina php PHP 1
D protezione cartelle: blocco visualizzazione/scaricamento contenuto, ma abilitazione utilizzo dati da parte di file .php presenti sul sito Web Server 1
F Php date_diff PHP 1
K [PHP] Aggiungere caratteri ad una stringa in base alla lunghezza della stessa PHP 2
C Wp-admin a file php WordPress 5
Lino80 [Retribuito] Cerco programmatore php per modifica/inserimento funzione/valori da un plugin importer wordpress Offerte e Richieste di Lavoro e/o Collaborazione 0
csi Inviare file jpg in locale alla stampante con php PHP 0
M Passaggio variabili array php su un tasto jq PHP 3
E Php aggiornamento tabella PHP 9
G phpmailer e php 8.1 con estensione mysqli PHP 6
M Invio dati database via email php PHP 0
K [php] Problema con inner join PHP 4
K [php]form invio dati PHP 0
P Codifica caratteri speciali mysql php PHP 0
K [PHP] Problema con variabili concatenate. PHP 1
E Stampante termica escpos-php PHP 6
JeiMax Modifica codice php personalizzato PHP 2
G Come modificare un pdf in php PHP 1
U Link a doppio file PHP PHP 0
E PHP & jQuery PHP 8
N Passare array da php a javascript PHP 5
F Applicazione PHP/MySQL per prenotazioni: limitare il numero massimo di posti prenotabili PHP 20
L tipo boolean non funzionante su mariadb (mysql). E codice php 7.4. PHP 0
U PHP creare un file excel dopo ricerca nel DB PHP 0
M PHP/MySQL - Estrarre valori min e max di ogni gruppo PHP 5
F Php e fatturazione elettronica PHP 0
P lanciare script asp (o php) da jquery Javascript 1
Couting95 inserire dati da un file di testo in una tabella in php PHP 1
P Data scraping in PHP non funziona PHP 4
C Calcoli matematici in php PHP 5
F Scrivere dei dati in word con php PHP 0
D PHP leggere cartella di Windows PHP 1
I dominio aruba versione php server linux Domini 3
G Colorare menu select attraverso ricerca php PHP 0
L PHP motore di ricerca nel sito PHP 1
S PHP e Mysqli PHP 0
Y Stampare da php su un foglio A6 attraverso una stampante esterna PHP 1

Discussioni simili