PHP的时间间隔至少为十天

时间:2016-01-01 13:47:00

标签: php mysql json pdo

这个想法是查询用户最新个人资料更改的最新时间戳。如果在尝试更新时不到十天,他们将被拒绝。无论我做什么,我都无法正确地获得10天差异逻辑。 $ stamp是数据库中的Y-m-d日期格式。

    <?php
ini_set('display_errors',1);
$json=$_POST['user'];
$json=str_replace('\\','',$json);
$user=json_decode($json);
$pdo=new PDO('mysql://hostname=localhost;dbname=database', 'user', 'password');
$update = $pdo->prepare("update  `accounts` set  stamp=CURDATE(),`title`='{$user->title}' ,`radio_hanlde`='{$user->radio_handle}' , `carrier`='{$user->carrier}' ,`hometown`='{$user->hometown}'  WHERE user_id='{$user->user_id}' AND DATE_DIFF(CURRDATE(),stamp) > 10");
$update->execute();
if ($update->rowCount() != 0 ){
     echo json_encode(array('success'=>'1','message'=>'Your profile has been updated successfully!'));} 
     else {echo json_encode(array('success'=>'0','message'=>'It has been less than ten days since your latest profile change. You will have to wait!'));}
?>

5 个答案:

答案 0 :(得分:1)

函数strtotime以秒为单位返回时间戳,因此您可以在几秒钟内获得非常简单的差异

$secs = strtotime('now') - strtotime($stamp);
$days = $secs / 60 / 60 / 24;
if($days <= 10) {
    ..your code...
}

答案 1 :(得分:1)

PHP的mysqli和PDO API具有检测UPDATE是否影响任何行(mysqli_affected_rows()和PDOStatement :: rowCount())的功能,因此您几乎可以丢弃所有代码。

您需要做的就是为给定用户更新符合条件的所有行,例如:

UPDATE accounts
   SET stamp = '$stamp'
     , title = '{$user->title}' 
     , radio_hanlde [SIC] ='{$user->radio_handle}' 
     , carrier  = '{$user->carrier}' 
     , hometown = '{$user->hometown}'
 WHERE user_id  = '{$user->user_id}'
   AND DATEDIFF(CURDATE(),stamp) > 10;

如果PDOStatement :: rowCount()返回0以外的值,则打印消息1,否则打印消息2.

根据以下示例,由OP组装......

$pdo->exec("
UPDATE accounts 
   SET stamp = '$stamp'
     , title = '{$user->title}'
     , radio_hanlde ='{$user->radio_handle}'
     , carrier = '{$user->carrier}'
     , hometown = '{$user->hometown}' 
 WHERE user_id = '{$user->user_id}' 
   AND DATEDIFF(CURDATE(),stamp) > 10
 "); 

if (PDOStatement::rowCount() < 1 ){
     echo json_encode(array('success'=>'0','message'=>'It has been less than ten days since your latest profile change. You will have to wait!'));
 } else {
     echo json_encode(array('success'=>'1','message'=>'Your profile has been updated successfully!'));
 }

答案 2 :(得分:0)

 $today=date_create(date('Y-m-d'));
 $date2=date_create("2013-12-12");
 $diff=date_diff($today,$date2);

if($diff<10){
  echo "Your alert";
}

答案 3 :(得分:0)

 $querydata="SELECT CURDATE()";
                                 $result_data= mysqli_query($link, $querydata);
                                  $data=mysqli_fetch_array($result_data)[0];
                                $intervaloTempo = gmdate("d:H:i:s", time() + (10 * 24 * 60 * 60);

将此用于您的查询

 "(().data=\"".$data."\" and ()>=\"".$intervaloTempo."\"" )"

                                    $query = sprintf("select stamp from accounts where user_id='{$user->user_id}, mysqli_real_escape_string($link, $_SESSION['cliente_id']));
                                    $result = mysqli_query($link, $query);
                                    if (!$result) {
                                        die("Query error: " . mysqli_error($link));
                                        //con_close();
                                    }

答案 4 :(得分:0)

使用time()函数获取当前时间(以秒为单位)(Unix时间戳)和strtotime()以将任何日期格式转换为时间戳。以下是您的示例的重构代码:

<?php

ini_set('display_errors', 1);

$messages = [
    'error_invalid_json' => 'Error. Invalid json',
    'error_account_not_found' => 'Error. Account is not found',
    'success' => 'Your profile has been updated successfully!',
    'wait_1_day' => 'It has been less than ten days since your latest profile change. You must wait until tomorrow!',
    'wait_n_days' => 'It has been less than ten days since your latest profile change. You have %s more to go!',
];

function message($message, $success = true)
{
    echo json_encode([
        'success' => ($success) ? 1 : 0,
        'message' => $message,
    ]);

    exit;
}

// get and validate incoming data
$json = $_POST['user'];
$json = str_replace('\\', '', $json);
if (empty($json)) {
    message($messages['error_invalid_json'], false);
}
try {
    $user = json_decode($json);
} catch (\Exception $e) {
    message($messages['error_invalid_json'], false);
}
if (empty($user->user_id)) {
    message($messages['error_invalid_json'], false);
}

// find last modified date
$pdo = new PDO('mysql://mydb', 'a_user', 'password');
$query = $pdo->query("Select stamp FROM accounts WHERE user_id='{$user->user_id}' LIMIT 1");
$stamp = $query->fetchAll(PDO::FETCH_ASSOC);
if (empty($stamp)) {
    message($messages['error_account_not_found']);
}

// calculcate when user is allowed to change profile
$daysShouldPassBeforeEdit = 10;
$allowEditAfter = ($stamp[1]) ? strtotime($stamp[1]) + $daysShouldPassBeforeEdit * 86400 : time(); // if empty `stamp` then user have not edited and allow to edit now

if (time() < $allowEditAfter) {
    $daysLeftBeforeAllowEdit = ceil(($allowEditAfter - time()) / 86400);

    if ($daysLeftBeforeAllowEdit == 1) {
        message($messages['wait_1_day'], false);
    } else {
        message(sprintf($messages['wait_n_days'], $daysLeftBeforeAllowEdit), false);
    }
}

// save changes
$stamp = date("Y-m-d");
$sql = "update  `accounts` set  stamp='$stamp',`title`='{$user->title}' ,`radio_hanlde`='{$user->radio_handle}' , `carrier`='{$user->carrier}' ,`hometown`='{$user->hometown}'  where user_id='{$user->user_id}'";
$pdo->exec($sql);
message($messages['success']);