Insert only a row if there is no longer a row for this day and this user

When someone first visits the X page, I insert a new row into the table with the current unix time ().

I want to insert new lines for this user every 24 hours .. so for example:

Example A) Bob, goes to my site, he inserts a line .. 12 hours later, Bob returns, he does not insert a new line, since 24 hours have not passed yet.

Example B) Bob, goes to my site, he inserts a line .. 24 hours later, Bob returns, he inserts a new line within 24 hours, passed.

I deal with this, but I can’t think if it’s right or not because my brain is fried.

$time = time();
$difference = 86400;
$timedifference = $time + $difference;

When inserting a row:

mysql_query("INSERT INTO `logs` (`time`, `who`, `site`, `type`) 
VALUES('" . $timedifference . "', '" . $ip . "', '" . $rid . "', 'out') ") 
or die(mysql_error()); 

When checking if it was 24 hours or more:

mysql_query("SELECT * FROM `logs` 
WHERE `time` < '" . time() . "' AND `type` = 'out' 
AND `site` = '" . $rid . "' AND `who` = '" . $ip . "'");

Can someone please tell me, right?

+3
4

. , :

//log check
$ip = ip2long($_SERVER['REMOTE_ADDR']);
$time = time(); //current time
$difference = 86400; //one day in seconds
$timedifference = $time + $difference; //time difference
$logQ = mysql_query("SELECT * FROM `logs` WHERE `time` > '" . time() . 
        "' AND `type` = 'out' AND `site` = '" . $id . 
        "' AND `who` = '" . $ip . "'");
$logR = mysql_num_rows($logQ);
if ($logR <= 0){
  mysql_query("INSERT INTO `logs` (`time`, `who`, `site`, `type`) VALUES('" . 
  $timedifference . "', '" . $ip . "', '" . $id . "', 'out') ") or 
  die(mysql_error());  
}
+2

Try

insert ignore into logs
  select unix_timestamp(now()), who, site, type
  from logs
  where 
  who='{$ip}' and 
  site='{$rid}' and
  type='out' and
  unix_timestamp(time)<=unix_timestamp(now())-86400 limit 1;

, return affected_rows,
, .

+1
  • $time, $timedifference.
  • , time time() - 86400. time a datetime, .
0

, 24 , , , , .

:

Create an index for entries for login time.
SELECT the last entry for this upstream index for the user ("who").
If the last and last is less than 24 hours from now (time ()), skip creating a new record.
Otherwise, create it now (time ()).

0
source

Source: https://habr.com/ru/post/1777056/


All Articles