从数据库表获取最新数据

时间:2019-02-13 06:10:01

标签: php sql-server

我只是想从数据库表中获取最新记录,使用LIMIT时出现此错误?

  

已建立连接。

Array ( [0] => Array ( [0] => 42000 [SQLSTATE] => 42000 [1] => 102 [code] => 102 [2] => [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]Incorrect syntax near 'LIMIT'. [message] => [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]Incorrect syntax near 'LIMIT'. ) )


$query = 'SELECT EventTime, EventHumidity, EventTemperature FROM TxnFMISHumidityTempEvent ORDER BY EventID DESC LIMIT 1';
$stmt = sqlsrv_query( $conn, $query );
if( $stmt === false) 
{
    die( print_r( sqlsrv_errors(), true) );
}

while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) 
{
    $css_class=' class="row"';
    echo "<tr '.$css_class.'>";
    echo "<td>SNSRP001</td>";
    echo "<td>MIS</td>";                
    echo "<td>" .$Date = $row['EventTime']->format('Y-m-d H:i:s'). "</td>";
    echo "<td>" .$row['EventHumidity'].  "</td>";
    echo "<td>" .$row['EventTemperature'].  "</td>";
    echo "</tr>";
}
sqlsrv_free_stmt( $stmt);

2 个答案:

答案 0 :(得分:0)

LIMIT在SQL Server中不受支持,您可以使用TOP 1代替LIMITORDER BY

按如下所示更改您的@query

$query = 'SELECT TOP 1 EventTime, EventHumidity, EventTemperature FROM TxnFMISHumidityTempEvent ORDER BY EventID DESC';

答案 1 :(得分:0)

尝试选择*以选择所有数据。

SELECT * FROM TxnFMISHumidityTempEvent ORDER BY primaryKeyId DESC LIMIT 1;