我正在尝试从MS SQL Server获取按当前时间过滤的列数据。单元格具有datetime
格式。但是我得到了空洞的回应。哪里有错?
<?php
$serverName = ''; // server name
$cinfo = array(
"Database" => "", // database
"UID" => "", // user
"PWD" => "" // pass
);
$conn = sqlsrv_connect($serverName, $cinfo);
if ($conn) {
echo "connected" . "<br/>";
$datetimenow = current_time("d.m.Y H:i"); // wordpress function
echo $datetimenow . "<br/>"; // 30.05.2020 14:10
if (($result = sqlsrv_query($conn, "SELECT * FROM dbo.GorElectroTrans WHERE GPS_datetime=$datetimenow")) !== false) {
while ($obj = sqlsrv_fetch_object($result)) {
echo $obj->Longitude . '<br />';
}
}
} else {
die(print_r(sqlsrv_errors(), true));
}
?>
您需要考虑以下因素:
datetime
变量的值使用明确的$datetimenow
格式。注意,在您的情况下,函数current_time
返回当前时间作为格式化的PHP datetime对象。datetime
值默认为returned作为PHP datetime
对象,因此您需要在连接字符串或语句级别设置'ReturnDatesAsStrings'
选项。PHP:
<?php
$serverName = ''; // server name
$cinfo = array(
"Database" => "", // database
"UID" => "", // user
"PWD" => "" // pass
);
$conn = sqlsrv_connect($serverName, $cinfo);
if ($conn) {
echo "connected" . "<br/>";
$datetimenow = current_time("Y-m-d\TH:i:00");
// or if you want a specific datetime value
//$datetimenow = '2020-05-30T14:10:00';
$sql = "SELECT * FROM dbo.GorElectroTrans WHERE GPS_datetime = ?";
$params = array($datetimenow);
if (($result = sqlsrv_query($conn, $sql, $params)) !== false) {
while ($obj = sqlsrv_fetch_object($result)) {
echo $obj->Longitude . '<br />';
}
}
} else {
die(print_r(sqlsrv_errors(), true));
}
?>