What is the best way to count page views in PHP/MySQL?
up vote
35
down vote
favorite
And by best I mean most efficient, right now placing this on my post.php file is the only thing I can think of:
$query = mysql_query(" UPDATE posts SET views + 1 WHERE id = '$id' ");
is there a better way, a method that would consume less server resources. I ask because if this was a small app I would have no problem with the above, but I am trying to build something that will be used by a lot of people and I want to be as query conscious as possible.
php mysql
add a comment |
up vote
35
down vote
favorite
And by best I mean most efficient, right now placing this on my post.php file is the only thing I can think of:
$query = mysql_query(" UPDATE posts SET views + 1 WHERE id = '$id' ");
is there a better way, a method that would consume less server resources. I ask because if this was a small app I would have no problem with the above, but I am trying to build something that will be used by a lot of people and I want to be as query conscious as possible.
php mysql
You could skip PHP/MySQL and use files instead.
– good_evening
May 14 '11 at 23:44
add a comment |
up vote
35
down vote
favorite
up vote
35
down vote
favorite
And by best I mean most efficient, right now placing this on my post.php file is the only thing I can think of:
$query = mysql_query(" UPDATE posts SET views + 1 WHERE id = '$id' ");
is there a better way, a method that would consume less server resources. I ask because if this was a small app I would have no problem with the above, but I am trying to build something that will be used by a lot of people and I want to be as query conscious as possible.
php mysql
And by best I mean most efficient, right now placing this on my post.php file is the only thing I can think of:
$query = mysql_query(" UPDATE posts SET views + 1 WHERE id = '$id' ");
is there a better way, a method that would consume less server resources. I ask because if this was a small app I would have no problem with the above, but I am trying to build something that will be used by a lot of people and I want to be as query conscious as possible.
php mysql
php mysql
asked Jan 21 '11 at 18:40
Joe
190145
190145
You could skip PHP/MySQL and use files instead.
– good_evening
May 14 '11 at 23:44
add a comment |
You could skip PHP/MySQL and use files instead.
– good_evening
May 14 '11 at 23:44
You could skip PHP/MySQL and use files instead.
– good_evening
May 14 '11 at 23:44
You could skip PHP/MySQL and use files instead.
– good_evening
May 14 '11 at 23:44
add a comment |
6 Answers
6
active
oldest
votes
up vote
57
down vote
accepted
If you're interested in conserving resources and still using SQL for reporting, and precise # doesn't matter, you could try sampling like this (modify sample rate to suit your scale):
$sample_rate = 100;
if(mt_rand(1,$sample_rate) == 1) {
$query = mysql_query(" UPDATE posts SET views = views + {$sample_rate} WHERE id = '{$id}' ");
// execute query, etc
}
Depending on how big "a lot of users" is, it may be beneficial to avoid MySQL on any tables that could get long. A good rule of thumb is this: If any collection (table) can get past 10 million records during your app's lifetime, you should probably not store that collection in MySQL. I recommend investigating MongoDB and Membase before it's too late!
– Kyle Wild
Jan 21 '11 at 18:49
@dorkitude, do you have any further information / reference for this rule? We have tables in the tens of billions of rows without problem. Not saying that MongoDB / memcached aren't a good resource, just wondering where we can find more information.
– jasonbar
Jan 23 '11 at 0:23
10
I'm not sure I follow, could someone explain what this does? It doesn't make sense to me. What is this good for?
– user1831020
Jan 29 '13 at 21:37
10
@Suyash This code is generating a random number between 1 and 100 - IF and only if the random number turns out to be '1', then the database value holding the view count will be incremented by 100. The general idea behind this is that, in theory, it should take 100 tries to hit the number '1' - and so the view count is more or less correct without the constant need to query the database.
– user725913
Mar 13 '13 at 3:20
1
It just uses probability. Sure there may be examples of results being way off at the beginning but generally the views will be correct - and the more views that come through, the more accurate this will be overall. The other point is that view count isn't such an essential part of the data in most apps.
– Ryall
Aug 9 '13 at 14:35
|
show 5 more comments
up vote
17
down vote
If memcache is an option in your server environment, here's another cool way to sample, but also keep up with the precise number (unlike my other answer):
function recordPostPageView($page_id) {
$memcache = new Memcached(); // you could also pull this instance from somewhere else, if you want a bit more efficiency*
$key = "Counter for Post {$page_id}";
if(!$memcache->get($key)) {
$memcache->set($key, 0);
}
$new_count = $memcache->increment($key);
// you could uncomment the following if you still want to notify mysql of the value occasionally
/*
$notify_mysql_interval = 100;
if($new_count % $notify_mysql_interval == 0) {
$query = mysql_query("UPDATE posts SET views = {$new_count} WHERE id = '{$page_id}' ");
// execute query, etc
}
*/
return $new_count;
}
- And don't mind purists crying foul about Singletons. Or you could pass it into this function, if you're more purist than pragmatist :)
setting up memcached and the confusion between memcache and memcached aside, this was an extremely elegant solution and the benchmarking results are very happy as well! Thanks for the awesome info.
– Suyash
Mar 7 '13 at 11:06
This works perfectly, as an improvement pass the count value from the database into the function as an extra variable, then use this value to set the memcache key. This way your counter stays in sync (plus or minus your interval value) if memcache is restarted.
– paj
Mar 8 '13 at 9:41
@paj Or you could simply flush your Memcache on each cronjob and start afresh, only adding up the count in the db by using count= count + memcache(getkey)
– Suyash
Mar 14 '13 at 3:43
add a comment |
up vote
6
down vote
IMHO best solution is to have views_count stored inside memory (memcached, whatever),
and do updates in memory. (Of course updates have to be synchronized)
Then you can use cron script which will push those values to db. (after some time - seconds, minutes, whatever.)
add a comment |
up vote
4
down vote
You can also check these lines of code. I think it will be helpful because you can achieve your goal with just a text file. It does not require any database activity.
<?php
session_start();
$counter_name = "counter.txt";
// Check if a text file exists. If not create one and initialize it to zero.
if (!file_exists($counter_name)) {
$f = fopen($counter_name, "w");
fwrite($f,"0");
fclose($f);
}
// Read the current value of our counter file
$f = fopen($counter_name,"r");
$counterVal = fread($f, filesize($counter_name));
fclose($f);
// Has visitor been counted in this session?
// If not, increase counter value by one
if(!isset($_SESSION['hasVisited'])){
$_SESSION['hasVisited']="yes";
$counterVal++;
$f = fopen($counter_name, "w");
fwrite($f, $counterVal);
fclose($f);
}
echo "You are visitor number $counterVal to this site";add a comment |
up vote
2
down vote
You could keep a counter-array in cache (like APC or Memcache) and increase the counter for certain posts in that. Then store the updates once a while. You might loose some views if a cache-reset occures
Other solution would be to keep a separate table for visits only (Field: postid, visits). That is the fasters you can get from mysql. Try to use InnoDB engine, since it provides row-level-locking!
add a comment |
up vote
2
down vote
in the database there is only one column ip with primary key defined and then store ip in database using PHP code below:
Connection file :
<?php
$conn = mysqli_connect("localhost","root","");
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$db=mysqli_select_db($conn,"DB_NAME");
if(!$db)
{
echo "Connection failed";
}
?>
PHP file:
<?php
$ip=$_SERVER['REMOTE_ADDR'];
$insert="INSERT INTO `id928751_photography`.`ip` (`ip`)VALUES ('$ip');";
$result = mysqli_query($conn,$insert);
?>
show count :
<?php
$select="SELECT COUNT(ip) as count from ip;";
$run= mysqli_query($conn,$select);
$res=mysqli_fetch_array($run);
echo $res['count'];
?>
using this method in the database store all server ip
NOTE: only server ip can store or count not device ip
add a comment |
6 Answers
6
active
oldest
votes
6 Answers
6
active
oldest
votes
active
oldest
votes
active
oldest
votes
up vote
57
down vote
accepted
If you're interested in conserving resources and still using SQL for reporting, and precise # doesn't matter, you could try sampling like this (modify sample rate to suit your scale):
$sample_rate = 100;
if(mt_rand(1,$sample_rate) == 1) {
$query = mysql_query(" UPDATE posts SET views = views + {$sample_rate} WHERE id = '{$id}' ");
// execute query, etc
}
Depending on how big "a lot of users" is, it may be beneficial to avoid MySQL on any tables that could get long. A good rule of thumb is this: If any collection (table) can get past 10 million records during your app's lifetime, you should probably not store that collection in MySQL. I recommend investigating MongoDB and Membase before it's too late!
– Kyle Wild
Jan 21 '11 at 18:49
@dorkitude, do you have any further information / reference for this rule? We have tables in the tens of billions of rows without problem. Not saying that MongoDB / memcached aren't a good resource, just wondering where we can find more information.
– jasonbar
Jan 23 '11 at 0:23
10
I'm not sure I follow, could someone explain what this does? It doesn't make sense to me. What is this good for?
– user1831020
Jan 29 '13 at 21:37
10
@Suyash This code is generating a random number between 1 and 100 - IF and only if the random number turns out to be '1', then the database value holding the view count will be incremented by 100. The general idea behind this is that, in theory, it should take 100 tries to hit the number '1' - and so the view count is more or less correct without the constant need to query the database.
– user725913
Mar 13 '13 at 3:20
1
It just uses probability. Sure there may be examples of results being way off at the beginning but generally the views will be correct - and the more views that come through, the more accurate this will be overall. The other point is that view count isn't such an essential part of the data in most apps.
– Ryall
Aug 9 '13 at 14:35
|
show 5 more comments
up vote
57
down vote
accepted
If you're interested in conserving resources and still using SQL for reporting, and precise # doesn't matter, you could try sampling like this (modify sample rate to suit your scale):
$sample_rate = 100;
if(mt_rand(1,$sample_rate) == 1) {
$query = mysql_query(" UPDATE posts SET views = views + {$sample_rate} WHERE id = '{$id}' ");
// execute query, etc
}
Depending on how big "a lot of users" is, it may be beneficial to avoid MySQL on any tables that could get long. A good rule of thumb is this: If any collection (table) can get past 10 million records during your app's lifetime, you should probably not store that collection in MySQL. I recommend investigating MongoDB and Membase before it's too late!
– Kyle Wild
Jan 21 '11 at 18:49
@dorkitude, do you have any further information / reference for this rule? We have tables in the tens of billions of rows without problem. Not saying that MongoDB / memcached aren't a good resource, just wondering where we can find more information.
– jasonbar
Jan 23 '11 at 0:23
10
I'm not sure I follow, could someone explain what this does? It doesn't make sense to me. What is this good for?
– user1831020
Jan 29 '13 at 21:37
10
@Suyash This code is generating a random number between 1 and 100 - IF and only if the random number turns out to be '1', then the database value holding the view count will be incremented by 100. The general idea behind this is that, in theory, it should take 100 tries to hit the number '1' - and so the view count is more or less correct without the constant need to query the database.
– user725913
Mar 13 '13 at 3:20
1
It just uses probability. Sure there may be examples of results being way off at the beginning but generally the views will be correct - and the more views that come through, the more accurate this will be overall. The other point is that view count isn't such an essential part of the data in most apps.
– Ryall
Aug 9 '13 at 14:35
|
show 5 more comments
up vote
57
down vote
accepted
up vote
57
down vote
accepted
If you're interested in conserving resources and still using SQL for reporting, and precise # doesn't matter, you could try sampling like this (modify sample rate to suit your scale):
$sample_rate = 100;
if(mt_rand(1,$sample_rate) == 1) {
$query = mysql_query(" UPDATE posts SET views = views + {$sample_rate} WHERE id = '{$id}' ");
// execute query, etc
}
If you're interested in conserving resources and still using SQL for reporting, and precise # doesn't matter, you could try sampling like this (modify sample rate to suit your scale):
$sample_rate = 100;
if(mt_rand(1,$sample_rate) == 1) {
$query = mysql_query(" UPDATE posts SET views = views + {$sample_rate} WHERE id = '{$id}' ");
// execute query, etc
}
edited Jan 21 '11 at 18:50
answered Jan 21 '11 at 18:44
Kyle Wild
7,13222635
7,13222635
Depending on how big "a lot of users" is, it may be beneficial to avoid MySQL on any tables that could get long. A good rule of thumb is this: If any collection (table) can get past 10 million records during your app's lifetime, you should probably not store that collection in MySQL. I recommend investigating MongoDB and Membase before it's too late!
– Kyle Wild
Jan 21 '11 at 18:49
@dorkitude, do you have any further information / reference for this rule? We have tables in the tens of billions of rows without problem. Not saying that MongoDB / memcached aren't a good resource, just wondering where we can find more information.
– jasonbar
Jan 23 '11 at 0:23
10
I'm not sure I follow, could someone explain what this does? It doesn't make sense to me. What is this good for?
– user1831020
Jan 29 '13 at 21:37
10
@Suyash This code is generating a random number between 1 and 100 - IF and only if the random number turns out to be '1', then the database value holding the view count will be incremented by 100. The general idea behind this is that, in theory, it should take 100 tries to hit the number '1' - and so the view count is more or less correct without the constant need to query the database.
– user725913
Mar 13 '13 at 3:20
1
It just uses probability. Sure there may be examples of results being way off at the beginning but generally the views will be correct - and the more views that come through, the more accurate this will be overall. The other point is that view count isn't such an essential part of the data in most apps.
– Ryall
Aug 9 '13 at 14:35
|
show 5 more comments
Depending on how big "a lot of users" is, it may be beneficial to avoid MySQL on any tables that could get long. A good rule of thumb is this: If any collection (table) can get past 10 million records during your app's lifetime, you should probably not store that collection in MySQL. I recommend investigating MongoDB and Membase before it's too late!
– Kyle Wild
Jan 21 '11 at 18:49
@dorkitude, do you have any further information / reference for this rule? We have tables in the tens of billions of rows without problem. Not saying that MongoDB / memcached aren't a good resource, just wondering where we can find more information.
– jasonbar
Jan 23 '11 at 0:23
10
I'm not sure I follow, could someone explain what this does? It doesn't make sense to me. What is this good for?
– user1831020
Jan 29 '13 at 21:37
10
@Suyash This code is generating a random number between 1 and 100 - IF and only if the random number turns out to be '1', then the database value holding the view count will be incremented by 100. The general idea behind this is that, in theory, it should take 100 tries to hit the number '1' - and so the view count is more or less correct without the constant need to query the database.
– user725913
Mar 13 '13 at 3:20
1
It just uses probability. Sure there may be examples of results being way off at the beginning but generally the views will be correct - and the more views that come through, the more accurate this will be overall. The other point is that view count isn't such an essential part of the data in most apps.
– Ryall
Aug 9 '13 at 14:35
Depending on how big "a lot of users" is, it may be beneficial to avoid MySQL on any tables that could get long. A good rule of thumb is this: If any collection (table) can get past 10 million records during your app's lifetime, you should probably not store that collection in MySQL. I recommend investigating MongoDB and Membase before it's too late!
– Kyle Wild
Jan 21 '11 at 18:49
Depending on how big "a lot of users" is, it may be beneficial to avoid MySQL on any tables that could get long. A good rule of thumb is this: If any collection (table) can get past 10 million records during your app's lifetime, you should probably not store that collection in MySQL. I recommend investigating MongoDB and Membase before it's too late!
– Kyle Wild
Jan 21 '11 at 18:49
@dorkitude, do you have any further information / reference for this rule? We have tables in the tens of billions of rows without problem. Not saying that MongoDB / memcached aren't a good resource, just wondering where we can find more information.
– jasonbar
Jan 23 '11 at 0:23
@dorkitude, do you have any further information / reference for this rule? We have tables in the tens of billions of rows without problem. Not saying that MongoDB / memcached aren't a good resource, just wondering where we can find more information.
– jasonbar
Jan 23 '11 at 0:23
10
10
I'm not sure I follow, could someone explain what this does? It doesn't make sense to me. What is this good for?
– user1831020
Jan 29 '13 at 21:37
I'm not sure I follow, could someone explain what this does? It doesn't make sense to me. What is this good for?
– user1831020
Jan 29 '13 at 21:37
10
10
@Suyash This code is generating a random number between 1 and 100 - IF and only if the random number turns out to be '1', then the database value holding the view count will be incremented by 100. The general idea behind this is that, in theory, it should take 100 tries to hit the number '1' - and so the view count is more or less correct without the constant need to query the database.
– user725913
Mar 13 '13 at 3:20
@Suyash This code is generating a random number between 1 and 100 - IF and only if the random number turns out to be '1', then the database value holding the view count will be incremented by 100. The general idea behind this is that, in theory, it should take 100 tries to hit the number '1' - and so the view count is more or less correct without the constant need to query the database.
– user725913
Mar 13 '13 at 3:20
1
1
It just uses probability. Sure there may be examples of results being way off at the beginning but generally the views will be correct - and the more views that come through, the more accurate this will be overall. The other point is that view count isn't such an essential part of the data in most apps.
– Ryall
Aug 9 '13 at 14:35
It just uses probability. Sure there may be examples of results being way off at the beginning but generally the views will be correct - and the more views that come through, the more accurate this will be overall. The other point is that view count isn't such an essential part of the data in most apps.
– Ryall
Aug 9 '13 at 14:35
|
show 5 more comments
up vote
17
down vote
If memcache is an option in your server environment, here's another cool way to sample, but also keep up with the precise number (unlike my other answer):
function recordPostPageView($page_id) {
$memcache = new Memcached(); // you could also pull this instance from somewhere else, if you want a bit more efficiency*
$key = "Counter for Post {$page_id}";
if(!$memcache->get($key)) {
$memcache->set($key, 0);
}
$new_count = $memcache->increment($key);
// you could uncomment the following if you still want to notify mysql of the value occasionally
/*
$notify_mysql_interval = 100;
if($new_count % $notify_mysql_interval == 0) {
$query = mysql_query("UPDATE posts SET views = {$new_count} WHERE id = '{$page_id}' ");
// execute query, etc
}
*/
return $new_count;
}
- And don't mind purists crying foul about Singletons. Or you could pass it into this function, if you're more purist than pragmatist :)
setting up memcached and the confusion between memcache and memcached aside, this was an extremely elegant solution and the benchmarking results are very happy as well! Thanks for the awesome info.
– Suyash
Mar 7 '13 at 11:06
This works perfectly, as an improvement pass the count value from the database into the function as an extra variable, then use this value to set the memcache key. This way your counter stays in sync (plus or minus your interval value) if memcache is restarted.
– paj
Mar 8 '13 at 9:41
@paj Or you could simply flush your Memcache on each cronjob and start afresh, only adding up the count in the db by using count= count + memcache(getkey)
– Suyash
Mar 14 '13 at 3:43
add a comment |
up vote
17
down vote
If memcache is an option in your server environment, here's another cool way to sample, but also keep up with the precise number (unlike my other answer):
function recordPostPageView($page_id) {
$memcache = new Memcached(); // you could also pull this instance from somewhere else, if you want a bit more efficiency*
$key = "Counter for Post {$page_id}";
if(!$memcache->get($key)) {
$memcache->set($key, 0);
}
$new_count = $memcache->increment($key);
// you could uncomment the following if you still want to notify mysql of the value occasionally
/*
$notify_mysql_interval = 100;
if($new_count % $notify_mysql_interval == 0) {
$query = mysql_query("UPDATE posts SET views = {$new_count} WHERE id = '{$page_id}' ");
// execute query, etc
}
*/
return $new_count;
}
- And don't mind purists crying foul about Singletons. Or you could pass it into this function, if you're more purist than pragmatist :)
setting up memcached and the confusion between memcache and memcached aside, this was an extremely elegant solution and the benchmarking results are very happy as well! Thanks for the awesome info.
– Suyash
Mar 7 '13 at 11:06
This works perfectly, as an improvement pass the count value from the database into the function as an extra variable, then use this value to set the memcache key. This way your counter stays in sync (plus or minus your interval value) if memcache is restarted.
– paj
Mar 8 '13 at 9:41
@paj Or you could simply flush your Memcache on each cronjob and start afresh, only adding up the count in the db by using count= count + memcache(getkey)
– Suyash
Mar 14 '13 at 3:43
add a comment |
up vote
17
down vote
up vote
17
down vote
If memcache is an option in your server environment, here's another cool way to sample, but also keep up with the precise number (unlike my other answer):
function recordPostPageView($page_id) {
$memcache = new Memcached(); // you could also pull this instance from somewhere else, if you want a bit more efficiency*
$key = "Counter for Post {$page_id}";
if(!$memcache->get($key)) {
$memcache->set($key, 0);
}
$new_count = $memcache->increment($key);
// you could uncomment the following if you still want to notify mysql of the value occasionally
/*
$notify_mysql_interval = 100;
if($new_count % $notify_mysql_interval == 0) {
$query = mysql_query("UPDATE posts SET views = {$new_count} WHERE id = '{$page_id}' ");
// execute query, etc
}
*/
return $new_count;
}
- And don't mind purists crying foul about Singletons. Or you could pass it into this function, if you're more purist than pragmatist :)
If memcache is an option in your server environment, here's another cool way to sample, but also keep up with the precise number (unlike my other answer):
function recordPostPageView($page_id) {
$memcache = new Memcached(); // you could also pull this instance from somewhere else, if you want a bit more efficiency*
$key = "Counter for Post {$page_id}";
if(!$memcache->get($key)) {
$memcache->set($key, 0);
}
$new_count = $memcache->increment($key);
// you could uncomment the following if you still want to notify mysql of the value occasionally
/*
$notify_mysql_interval = 100;
if($new_count % $notify_mysql_interval == 0) {
$query = mysql_query("UPDATE posts SET views = {$new_count} WHERE id = '{$page_id}' ");
// execute query, etc
}
*/
return $new_count;
}
- And don't mind purists crying foul about Singletons. Or you could pass it into this function, if you're more purist than pragmatist :)
edited Jan 21 '11 at 19:04
answered Jan 21 '11 at 18:58
Kyle Wild
7,13222635
7,13222635
setting up memcached and the confusion between memcache and memcached aside, this was an extremely elegant solution and the benchmarking results are very happy as well! Thanks for the awesome info.
– Suyash
Mar 7 '13 at 11:06
This works perfectly, as an improvement pass the count value from the database into the function as an extra variable, then use this value to set the memcache key. This way your counter stays in sync (plus or minus your interval value) if memcache is restarted.
– paj
Mar 8 '13 at 9:41
@paj Or you could simply flush your Memcache on each cronjob and start afresh, only adding up the count in the db by using count= count + memcache(getkey)
– Suyash
Mar 14 '13 at 3:43
add a comment |
setting up memcached and the confusion between memcache and memcached aside, this was an extremely elegant solution and the benchmarking results are very happy as well! Thanks for the awesome info.
– Suyash
Mar 7 '13 at 11:06
This works perfectly, as an improvement pass the count value from the database into the function as an extra variable, then use this value to set the memcache key. This way your counter stays in sync (plus or minus your interval value) if memcache is restarted.
– paj
Mar 8 '13 at 9:41
@paj Or you could simply flush your Memcache on each cronjob and start afresh, only adding up the count in the db by using count= count + memcache(getkey)
– Suyash
Mar 14 '13 at 3:43
setting up memcached and the confusion between memcache and memcached aside, this was an extremely elegant solution and the benchmarking results are very happy as well! Thanks for the awesome info.
– Suyash
Mar 7 '13 at 11:06
setting up memcached and the confusion between memcache and memcached aside, this was an extremely elegant solution and the benchmarking results are very happy as well! Thanks for the awesome info.
– Suyash
Mar 7 '13 at 11:06
This works perfectly, as an improvement pass the count value from the database into the function as an extra variable, then use this value to set the memcache key. This way your counter stays in sync (plus or minus your interval value) if memcache is restarted.
– paj
Mar 8 '13 at 9:41
This works perfectly, as an improvement pass the count value from the database into the function as an extra variable, then use this value to set the memcache key. This way your counter stays in sync (plus or minus your interval value) if memcache is restarted.
– paj
Mar 8 '13 at 9:41
@paj Or you could simply flush your Memcache on each cronjob and start afresh, only adding up the count in the db by using count= count + memcache(getkey)
– Suyash
Mar 14 '13 at 3:43
@paj Or you could simply flush your Memcache on each cronjob and start afresh, only adding up the count in the db by using count= count + memcache(getkey)
– Suyash
Mar 14 '13 at 3:43
add a comment |
up vote
6
down vote
IMHO best solution is to have views_count stored inside memory (memcached, whatever),
and do updates in memory. (Of course updates have to be synchronized)
Then you can use cron script which will push those values to db. (after some time - seconds, minutes, whatever.)
add a comment |
up vote
6
down vote
IMHO best solution is to have views_count stored inside memory (memcached, whatever),
and do updates in memory. (Of course updates have to be synchronized)
Then you can use cron script which will push those values to db. (after some time - seconds, minutes, whatever.)
add a comment |
up vote
6
down vote
up vote
6
down vote
IMHO best solution is to have views_count stored inside memory (memcached, whatever),
and do updates in memory. (Of course updates have to be synchronized)
Then you can use cron script which will push those values to db. (after some time - seconds, minutes, whatever.)
IMHO best solution is to have views_count stored inside memory (memcached, whatever),
and do updates in memory. (Of course updates have to be synchronized)
Then you can use cron script which will push those values to db. (after some time - seconds, minutes, whatever.)
answered May 15 '11 at 9:42
Kamil Tomšík
1,68321730
1,68321730
add a comment |
add a comment |
up vote
4
down vote
You can also check these lines of code. I think it will be helpful because you can achieve your goal with just a text file. It does not require any database activity.
<?php
session_start();
$counter_name = "counter.txt";
// Check if a text file exists. If not create one and initialize it to zero.
if (!file_exists($counter_name)) {
$f = fopen($counter_name, "w");
fwrite($f,"0");
fclose($f);
}
// Read the current value of our counter file
$f = fopen($counter_name,"r");
$counterVal = fread($f, filesize($counter_name));
fclose($f);
// Has visitor been counted in this session?
// If not, increase counter value by one
if(!isset($_SESSION['hasVisited'])){
$_SESSION['hasVisited']="yes";
$counterVal++;
$f = fopen($counter_name, "w");
fwrite($f, $counterVal);
fclose($f);
}
echo "You are visitor number $counterVal to this site";add a comment |
up vote
4
down vote
You can also check these lines of code. I think it will be helpful because you can achieve your goal with just a text file. It does not require any database activity.
<?php
session_start();
$counter_name = "counter.txt";
// Check if a text file exists. If not create one and initialize it to zero.
if (!file_exists($counter_name)) {
$f = fopen($counter_name, "w");
fwrite($f,"0");
fclose($f);
}
// Read the current value of our counter file
$f = fopen($counter_name,"r");
$counterVal = fread($f, filesize($counter_name));
fclose($f);
// Has visitor been counted in this session?
// If not, increase counter value by one
if(!isset($_SESSION['hasVisited'])){
$_SESSION['hasVisited']="yes";
$counterVal++;
$f = fopen($counter_name, "w");
fwrite($f, $counterVal);
fclose($f);
}
echo "You are visitor number $counterVal to this site";add a comment |
up vote
4
down vote
up vote
4
down vote
You can also check these lines of code. I think it will be helpful because you can achieve your goal with just a text file. It does not require any database activity.
<?php
session_start();
$counter_name = "counter.txt";
// Check if a text file exists. If not create one and initialize it to zero.
if (!file_exists($counter_name)) {
$f = fopen($counter_name, "w");
fwrite($f,"0");
fclose($f);
}
// Read the current value of our counter file
$f = fopen($counter_name,"r");
$counterVal = fread($f, filesize($counter_name));
fclose($f);
// Has visitor been counted in this session?
// If not, increase counter value by one
if(!isset($_SESSION['hasVisited'])){
$_SESSION['hasVisited']="yes";
$counterVal++;
$f = fopen($counter_name, "w");
fwrite($f, $counterVal);
fclose($f);
}
echo "You are visitor number $counterVal to this site";You can also check these lines of code. I think it will be helpful because you can achieve your goal with just a text file. It does not require any database activity.
<?php
session_start();
$counter_name = "counter.txt";
// Check if a text file exists. If not create one and initialize it to zero.
if (!file_exists($counter_name)) {
$f = fopen($counter_name, "w");
fwrite($f,"0");
fclose($f);
}
// Read the current value of our counter file
$f = fopen($counter_name,"r");
$counterVal = fread($f, filesize($counter_name));
fclose($f);
// Has visitor been counted in this session?
// If not, increase counter value by one
if(!isset($_SESSION['hasVisited'])){
$_SESSION['hasVisited']="yes";
$counterVal++;
$f = fopen($counter_name, "w");
fwrite($f, $counterVal);
fclose($f);
}
echo "You are visitor number $counterVal to this site";<?php
session_start();
$counter_name = "counter.txt";
// Check if a text file exists. If not create one and initialize it to zero.
if (!file_exists($counter_name)) {
$f = fopen($counter_name, "w");
fwrite($f,"0");
fclose($f);
}
// Read the current value of our counter file
$f = fopen($counter_name,"r");
$counterVal = fread($f, filesize($counter_name));
fclose($f);
// Has visitor been counted in this session?
// If not, increase counter value by one
if(!isset($_SESSION['hasVisited'])){
$_SESSION['hasVisited']="yes";
$counterVal++;
$f = fopen($counter_name, "w");
fwrite($f, $counterVal);
fclose($f);
}
echo "You are visitor number $counterVal to this site";<?php
session_start();
$counter_name = "counter.txt";
// Check if a text file exists. If not create one and initialize it to zero.
if (!file_exists($counter_name)) {
$f = fopen($counter_name, "w");
fwrite($f,"0");
fclose($f);
}
// Read the current value of our counter file
$f = fopen($counter_name,"r");
$counterVal = fread($f, filesize($counter_name));
fclose($f);
// Has visitor been counted in this session?
// If not, increase counter value by one
if(!isset($_SESSION['hasVisited'])){
$_SESSION['hasVisited']="yes";
$counterVal++;
$f = fopen($counter_name, "w");
fwrite($f, $counterVal);
fclose($f);
}
echo "You are visitor number $counterVal to this site";edited Nov 19 at 9:55
Collin ter Steege
577113
577113
answered Jan 19 '16 at 20:13
Click4Knowledge
413
413
add a comment |
add a comment |
up vote
2
down vote
You could keep a counter-array in cache (like APC or Memcache) and increase the counter for certain posts in that. Then store the updates once a while. You might loose some views if a cache-reset occures
Other solution would be to keep a separate table for visits only (Field: postid, visits). That is the fasters you can get from mysql. Try to use InnoDB engine, since it provides row-level-locking!
add a comment |
up vote
2
down vote
You could keep a counter-array in cache (like APC or Memcache) and increase the counter for certain posts in that. Then store the updates once a while. You might loose some views if a cache-reset occures
Other solution would be to keep a separate table for visits only (Field: postid, visits). That is the fasters you can get from mysql. Try to use InnoDB engine, since it provides row-level-locking!
add a comment |
up vote
2
down vote
up vote
2
down vote
You could keep a counter-array in cache (like APC or Memcache) and increase the counter for certain posts in that. Then store the updates once a while. You might loose some views if a cache-reset occures
Other solution would be to keep a separate table for visits only (Field: postid, visits). That is the fasters you can get from mysql. Try to use InnoDB engine, since it provides row-level-locking!
You could keep a counter-array in cache (like APC or Memcache) and increase the counter for certain posts in that. Then store the updates once a while. You might loose some views if a cache-reset occures
Other solution would be to keep a separate table for visits only (Field: postid, visits). That is the fasters you can get from mysql. Try to use InnoDB engine, since it provides row-level-locking!
answered Jan 21 '11 at 18:49
Mano Kovacs
1,23111015
1,23111015
add a comment |
add a comment |
up vote
2
down vote
in the database there is only one column ip with primary key defined and then store ip in database using PHP code below:
Connection file :
<?php
$conn = mysqli_connect("localhost","root","");
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$db=mysqli_select_db($conn,"DB_NAME");
if(!$db)
{
echo "Connection failed";
}
?>
PHP file:
<?php
$ip=$_SERVER['REMOTE_ADDR'];
$insert="INSERT INTO `id928751_photography`.`ip` (`ip`)VALUES ('$ip');";
$result = mysqli_query($conn,$insert);
?>
show count :
<?php
$select="SELECT COUNT(ip) as count from ip;";
$run= mysqli_query($conn,$select);
$res=mysqli_fetch_array($run);
echo $res['count'];
?>
using this method in the database store all server ip
NOTE: only server ip can store or count not device ip
add a comment |
up vote
2
down vote
in the database there is only one column ip with primary key defined and then store ip in database using PHP code below:
Connection file :
<?php
$conn = mysqli_connect("localhost","root","");
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$db=mysqli_select_db($conn,"DB_NAME");
if(!$db)
{
echo "Connection failed";
}
?>
PHP file:
<?php
$ip=$_SERVER['REMOTE_ADDR'];
$insert="INSERT INTO `id928751_photography`.`ip` (`ip`)VALUES ('$ip');";
$result = mysqli_query($conn,$insert);
?>
show count :
<?php
$select="SELECT COUNT(ip) as count from ip;";
$run= mysqli_query($conn,$select);
$res=mysqli_fetch_array($run);
echo $res['count'];
?>
using this method in the database store all server ip
NOTE: only server ip can store or count not device ip
add a comment |
up vote
2
down vote
up vote
2
down vote
in the database there is only one column ip with primary key defined and then store ip in database using PHP code below:
Connection file :
<?php
$conn = mysqli_connect("localhost","root","");
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$db=mysqli_select_db($conn,"DB_NAME");
if(!$db)
{
echo "Connection failed";
}
?>
PHP file:
<?php
$ip=$_SERVER['REMOTE_ADDR'];
$insert="INSERT INTO `id928751_photography`.`ip` (`ip`)VALUES ('$ip');";
$result = mysqli_query($conn,$insert);
?>
show count :
<?php
$select="SELECT COUNT(ip) as count from ip;";
$run= mysqli_query($conn,$select);
$res=mysqli_fetch_array($run);
echo $res['count'];
?>
using this method in the database store all server ip
NOTE: only server ip can store or count not device ip
in the database there is only one column ip with primary key defined and then store ip in database using PHP code below:
Connection file :
<?php
$conn = mysqli_connect("localhost","root","");
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$db=mysqli_select_db($conn,"DB_NAME");
if(!$db)
{
echo "Connection failed";
}
?>
PHP file:
<?php
$ip=$_SERVER['REMOTE_ADDR'];
$insert="INSERT INTO `id928751_photography`.`ip` (`ip`)VALUES ('$ip');";
$result = mysqli_query($conn,$insert);
?>
show count :
<?php
$select="SELECT COUNT(ip) as count from ip;";
$run= mysqli_query($conn,$select);
$res=mysqli_fetch_array($run);
echo $res['count'];
?>
using this method in the database store all server ip
NOTE: only server ip can store or count not device ip
edited Aug 29 '17 at 4:21
answered Jul 1 '17 at 4:44
pradip kor
30946
30946
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f4762527%2fwhat-is-the-best-way-to-count-page-views-in-php-mysql%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
You could skip PHP/MySQL and use files instead.
– good_evening
May 14 '11 at 23:44