简体   繁体   中英

PHP SQL Server: Trying to find most recent entry into a database by the column Date and Time

New to SQL and PHP so please be merciful and I see that this explanation is horrible so sorry in advance.

This query is returning false when ran. What I'm trying to do pull the most recent entry out of the database by the timestamp that is stored in the DateAndTime column that corresponds with the ID Row example .

My thinking is that I sort the rows by their dates and time then take the first row that corresponds to the ID.

$mostRecent_Query = "SELECT TOP 1 * 
FROM locationFTable 
ORDER BY DateAndTime DESC Where ID like $conID";

$resultTime = sqlsrv_query($conn, $mostRecent_Query);

Your SQL query is wrong, the WHERE... clause must appear before the ORDER BY... clause. For example:

SELECT TOP 1 * 
FROM locationFTable 
WHERE ID like $conID
ORDER BY DateAndTime DESC

Note : You should test your queries before putting them into your code. SQL Server Management Studio is perfect for this task.

Bonus Note : The ID column is likely an int so I am guessing that LIKE is the wrong operator to use, perhaps you meant to use = instead?

Bonus Bonus Note : Go and read up about SQL injection as your code is very likely vulnerable to that security risk.

$mostRecent_Query = "SELECT `location`, `DateAndTime` FROM locationFTable Where ID = $conI ORDER BY DateAndTime DESC";

Since you are using the procedural interface you need to verify manually the return value of all involved function calls, in this case sqlsrv_query() :

Returns a statement resource on success and FALSE if an error occurred.

In case of error, you then need to call sqlsrv_errors() to read them.

Last but not least, you are injecting data the wrong way.

You have a rough but comprehensive example in the documentation:

$sql = "INSERT INTO Table_1 (id, data) VALUES (?, ?)";
$params = array(1, "some data");

$stmt = sqlsrv_query( $conn, $sql, $params);
if( $stmt === false ) {
     die( print_r( sqlsrv_errors(), true));
}

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