How to show the number of page views of the site with PHP?

2

In my database in the paginas table I have the fields pagina_1 , pagina_2 and pagina_3 representing the three pages of my site.

In these fields I'll insert the page views as below.

In my "page one" code, for example:

<?php 
   $result = mysql_query( "SELECT pagina_1 FROM paginas" )
      or die ( mysql_error() ); 

   $row = mysql_fetch_assoc( $result );
   $visualizacoes = $row['pagina_1'];
   $visualizacoes_mais = $visualizacoes + 1;
   $sql = mysql_query( "UPDATE paginas SET pagina_1 ='$visualizacoes_mais' " )
      or die ( mysql_error() );
   ...
?>

With this code I get that every time a page is accessed, views are incremented.

Is it a good way to record views for each page? I know it's a relative question, but in the background I want to know if there is another way or if it's the same: will I have to create a field for every page my site has, whether it's 10, 100 or 1000 pages?     

asked by anonymous 01.05.2014 / 17:30

1 answer

4

Imagine the following:

You have a relational database, with tables. Tables we relate to rows and columns. Usually more rows than columns, in most cases.

Generally what varies in tables is the number of rows, not columns.

How about using the same system for your case?

pagina          | visitas
-------------------------
pagina_1        | 127
pagina_2        | 17
pagina_3        | 32
home_page       | 56
pagina_4        | 4

So, to know the count of visits would suffice this query:

$result = mysqli_query("SELECT visitas FROM paginas WHERE pagina='pagina_1'")
// só não usei binding aqui pelo exemplo ser literal.

And to update the number of visits:

$result = mysqli_query("UPDATE paginas SET visitas=visitas+1 WHERE pagina='pagina_1'")

I think it will save you a lot of headache:)

The best thing is that you can put this in a require_once( ) , and change only one variable.

$pagina = 'pagina_1';
require_once( 'contador.php' ); // em contador.php teriamos a parte do update.

If you prefer, you can simply put a $pagina = $_SERVER["PHP_SELF"]; in contador.php , and use the relative URL of the page as the identifier.

There, on every page you would only have this line:

require_once( 'contador.php' );

And no contador.php :

$pagina = $_SERVER["PHP_SELF"];

$minhaconexao = new mysqli( ... dados da conexao ... );
$stmt = $minhaconexao->stmt_init();
$stmt->prepare('UPDATE paginas SET visitas=visitas+1 WHERE pagina=?');
$stmt->bind_param('s', $pagina);
$stmt->execute();    

The only caution in this case is you pre-populate the multi-line table, and the page path, like this:

pagina          | visitas
-------------------------
/               | 0
/sobre.php      | 0
/contatos.php   | 0
...

and so on.

    
01.05.2014 / 19:33