php: only register visit 1 per hour
How can i only save one profilevisit per hour? So if you visited at 10:10 then it wont save when you view the profile at 12:10 ?
My code right now that saves evrytime you visit:
$date = time();
$BuID= mysql_real_escape_string($v["id"]);
$uID= mysql_real_escape_string($showU["id"]);
mysql_query("INSERT INTO users_profilevisits (uID, BuID, date) VALUES ('$uID', '$BuID', '$date')") or
die(mysql_error());
update
function save(){
mysql_query("INSERT INTO users_profilevisits (uID, BuID, date) VALUES ('$uID', '$BuID', '$date')") or
die(mysql_error());
$_SESSIO开发者_如何学编程N['saved']=time();
}
if(isset($_SESSION['saved'])){
$time = time();
if($time-$_SESSION['saved'] > 3600){
save();
}
}else{
save();
}
select the timestamp and conditionally execute the save based on timestamp. alternatively, set a session variable and conditionally execute based on that value.
if(isset($_SESSION['saved']){
$time = time();
if($time-$_SESSION['saved'] > 3600){
save($uid,$buid);
}else{
save($uid,$buid);
function save($uid,$buid){
//save stuff here
$_SESSION['saved']=time();
}
If you always set the minutes/seconds of the provided time to 0, you can create a key over date and BuID, so it wont be able to insert more than 1 row within a hour(without any checks, session-vars or subqueries).
If you need the minutes/seconds for further operations, create a new column for implementing the described method.
assuming the following table:
date INT(11)
uID INT(11)
BuID INT(11)
date2 TIMESTAMP
UNIQUE KEY `BuID` (`BuID`,`date2`)
the following query should match your needs:
INSERT INTO users_profilevisits (uID, BuID, date, date2)
VALUES ('$uID', '$BuID', '$date',FROM_UNIXTIME(UNIX_TIMESTAMP(),'%Y%m%d%H0000'))
As you have a unique key over BuID and date2(date2 will have a value of the current time with minutes and seconds set to 0), it wont be able to insert duplicate rows with the same date2+BuID
But you have to remove the or die()
, because if you try to insert a duplicate key, this will result in an error.
Using this method you dont need a programming logic, the table-structure itsselve will do the work for you.
Just give the MySQL table an additional field and set it to unique. When you save the visit, save a string like "visitoruserid+year+month+day+hour" to that field. That way MySQL takes care of only allowing one per hour per user without the need for additional PHP code, sessions and time checks.
Edit:
Add. benefit: If you later choose to loose the "once per hour" condition or change it to once per day or add more conditions, you only have to change the string saved to that field without any more changes to your code.
精彩评论