简体   繁体   中英

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

I need to fetch active records from my table. A record is active means it is not expired and the expiration time is 2 minutes after record is generated. I am using sql server database. Here is the structure for my table在此处输入图片说明

And my code is as follows

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

I need the condition for DateGenerated as

currenttime <= DateGenerated + 2 minutes

How can I implement this condition in my query

Another possible approach is to let the SQL Server do the check using 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);
?>

您可以使用DATEADD

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

Try this one, i haven't tested but it would be like this.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM