dongshou1991 2018-09-04 04:42
浏览 70
已采纳

根据php和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 enter image description here

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

  • 写回答

3条回答 默认 最新

  • doucheng9058 2018-09-04 05:45
    关注

    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);
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改