简体   繁体   English

PHP SQL Server:尝试通过“日期和时间”列查找数据库的最新条目

[英]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. SQL和PHP的新功能,所以请多加注意,我看到这个解释太可怕了,因此请提前对不起。

This query is returning false when ran. 运行时此查询返回false。 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 . 我正在尝试通过存储在与ID Row示例相对应的DateAndTime列中的时间戳将最新条目从数据库中拉出。

My thinking is that I sort the rows by their dates and time then take the first row that corresponds to the ID. 我的想法是,我按日期和时间对行进行排序,然后选择与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. 您的SQL查询错误, WHERE...子句必须出现 ORDER BY...子句之前。 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. SQL Server Management Studio非常适合此任务。

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? 注意ID列很可能是int所以我猜LIKE是错误的运算符,也许您想使用=代替?

Bonus Bonus Note : Go and read up about SQL injection as your code is very likely vulnerable to that security risk. 奖金奖金注意 :请继续阅读有关SQL注入的信息,因为您的代码很容易受到这种安全风险的攻击。

$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() : 由于您正在使用过程接口,因此需要手动验证所有涉及到的函数调用的返回值,在本例中为sqlsrv_query()

Returns a statement resource on success and FALSE if an error occurred. 返回成功的语句资源,如果发生错误则返回FALSE

In case of error, you then need to call sqlsrv_errors() to read them. 如果发生错误,则需要调用sqlsrv_errors()来读取它们。

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));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM