TS准备好的声明

时间:2017-05-30 15:03:13

标签: php sql-server sqlsrv

我在使用sqlsrv驱动程序的语法时遇到了问题。

这很好用:

  $sql = "SELECT * from Table1 WHERE (Table1.Time >= {ts '2017-05-08
          00:00:00' } AND Table1.Time < {ts '2017-05-10 00:00:00' })";
  $stmt = sqlsrv_query( $conn, $sql );

  $tbl = "<table>"
  while ($row = sqlsrv_fetch_array($stmt)){
      $tbl .= "<tr><td>".$row[0]."</td><td>".$row[1]->format('Y-m-d H:i:s')."</td><td align=\"center\">".$row[2]."</td></tr>";
  }
  $tbl .= "</table>";
  echo $tbl;

但这并不能解决所有问题:

      $sql = "SELECT * from Table1 WHERE (Table1.Time >= {ts ? } AND Table1.Time < {ts ? })";
      $stmt = sqlsrv_prepare( $conn, $sql, array('2017-05-08 00:00:00','2017-05-10 00:00:00'));
      $result = sqlsrv_execute($stmt);
      $tbl = "<table>"
      while ($row = sqlsrv_fetch_array($stmt)){
          $tbl .= "<tr><td>".$row[0]."</td><td>".$row[1]->format('Y-m-d H:i:s')."</td><td align=\"center\">".$row[2]."</td></tr>";
      }
      $tbl .= "</table>";
      echo $tbl;

我收到此错误:

An invalid parameter was passed to sqlsrv_execute. [message] => An invalid parameter was passed to sqlsrv_execute. )

是否有正确的方法将日期变量传递给{ ts ? }语句?

1 个答案:

答案 0 :(得分:2)

您不太可能准备好与ODBC escape sequences一起使用的语句。与MySQL(具有UNIX_TIMESTAMP函数)不同,SQL Server内置的函数不会为您转换为Unix时间戳。您可以自己do the math,但也许在PHP中更容易实现:

$begin = strtotime('2017-05-08 00:00:00');
$end = strtotime('2017-05-10 00:00:00');
$sql = "SELECT * FROM Table1 WHERE Table1.Time >= ? AND Table1.Time < ?)";
$stmt = sqlsrv_prepare($conn, $sql, array($begin, $end));
$result = sqlsrv_execute($stmt);
$tbl = "<table>"
while ($row = sqlsrv_fetch_array($stmt)){
    $row[1] = $row[1]->format('Y-m-d H:i:s');
    $tbl .= "<tr><td>$row[0]</td><td>$row[1]</td><td align=\"center\">$row[2]</td></tr>";
}
$tbl .= "</table>";
echo $tbl;

您应枚举您正在提取的列,而不是使用*,然后按名称(例如$row["Time"])而不是数字引用它们。它将使您的代码更具可读性,并保护它免受数据库模式的更改。