根据 php 和 sql 服务器中的日期时间从 table 中查找活动记录

find active records from table based on date time in php and sql server

我需要从我的 table 中获取活动记录。一条记录是活跃的意味着它没有过期,过期时间是记录生成后的 2 分钟。我正在使用 sql 服务器数据库。 这是我的 table 的结构

而我的代码如下

$serverName = "xxx.xx.x.xxx";
$connectionInfo = array( "Database"=>"xxxxxx", "UID"=>"xxxxx", "PWD"=>"xxxxxx");
$conn = sqlsrv_connect($serverName, $connectionInfo);   
if($conn)
    echo 'success';
else 
    echo "failed";

$currentTime = date('Y-m-d H:i:s');
$query = "SELECT * FROM ApiTockenMaster WHERE Tocken = ? AND DateGenerated <= ? AND Status = ?";
$params = array("xxxxxxx", "2018-09-03 18:06:17.7600000", "Generated");
$result = sqlsrv_query( $conn, $query, $params);
$row = sqlsrv_fetch_array($result);
echo '<pre>'; print_r($row);
echo count($row);

我需要 DateGenerated 作为

的条件
currenttime <= DateGenerated + 2 minutes

如何在我的查询中实现这个条件

您可以使用 DATEADD:

currenttime <= DATEADD(MINUTE, 2, DateGenerated);

试试这个,我没有测试过,但应该是这样的。

$currenttime= date("Y-m-d H:i:s",strtotime(date("Y-m-d H:i:s")." +2 minutes"));
$params = array("xxxxxxx", $currenttime, "Generated");

另一种可能的方法是让 SQL 服务器使用 CURRENT_TIMESTAMP and DATEADD():

进行检查
<?php
# Connection
$serverName = "xxx.xx.x.xxx";
$connectionInfo = array(
    "Database"=>"xxxxxx", 
    "UID"=>"xxxxx", 
    "PWD"=>"xxxxxx"
);
$conn = sqlsrv_connect($serverName, $connectionInfo);   
if ($conn) {
    echo "Connection established.<br />";
} else {
    echo "Connection could not be established.<br />";
    die(print_r(sqlsrv_errors(), true));
}

# Statement
$query = "
    SELECT * 
    FROM ApiTockenMaster 
    WHERE 
        (Tocken = ?) AND 
        (CURRENT_TIMESTAMP <= DATEADD(mi, 2, DateGenerated)) AND 
        (Status = ?)
";
$params = array(
    "xxxxxxx", 
    "Generated"
);
$result = sqlsrv_query($conn, $query, $params);
if ($result === false){
    die(print_r(sqlsrv_errors(), true));
}

# Result
$row = sqlsrv_fetch_array($result);
echo '<pre>'; 
print_r($row);
echo count($row);
?>