[英]Prepared statement with PHP and MSSQL
I have an odd scenario about pdos. 我对pdos有一个奇怪的设想。 With prepared statements I get 0 results from database.
使用准备好的语句,我从数据库中得到0个结果。 But hardcoded I get normal results.
但是硬编码我得到正常结果。 This is a sql query for mssql (< 2012) to get limited results.
这是mssql的SQL查询(<2012),以得到有限的结果。
Prepared Statement (just do not wonder about the top and offset variable. I'm setting those in the function just for testing purpose. Also $conn is edited for stackoverflow. The prepare function is reachable from the function, so there is no problem): 准备语句(只是不要怀疑top和offset变量。我只是为了测试目的在函数中设置它们。还为$ stackoverflow编辑了$ conn。prepare函数可以从该函数访问,所以没有问题) :
public function myFunction($top, $offset) {
try {
$top = 20;
$offset = 1;
$sql = "SELECT TOP :top * FROM (
SELECT *, ROW_NUMBER() OVER (ORDER BY id) AS t1
FROM myTable) AS nU WHERE t1 >= :offset";
$statement = $conn->prepare($sql);
$statement->execute(array(':top' => $top, ':offset' => $offset));
return $statement->fetchAll();
} catch (Exception $e) {
echo $e->getMessage();
}
}
Result is an array with 0 elements. 结果是一个包含0个元素的数组。
But with this it works perfectly: 但与此完美地工作:
public function myFunction($top, $offset) {
try {
$top = 20;
$offset = 1;
$sql = "SELECT TOP 20 * FROM (
SELECT *, ROW_NUMBER() OVER (ORDER BY id) AS t1
FROM myTable) AS nU WHERE t1 >= 1";
$statement = $conn->prepare($sql);
$statement->execute();
return $statement->fetchAll();
} catch (Exception $e) {
echo $e->getMessage();
}
}
With this I get results correctly. 这样我就可以正确地得到结果。
How this is possible? 这怎么可能? What's wrong with the prepared statement?
准备好的语句有什么问题? I have a lot of prepared statements and it worked fine before.
我有很多准备好的声明,以前效果很好。
Thanks for answers. 感谢您的回答。
@EDIT - updated code - still not working: @EDIT-更新的代码-仍然无法正常工作:
public function myFunction($top, $offset) {
try {
$top = 20;
$offset = 1;
$sql = "SELECT TOP :top * FROM (
SELECT *, ROW_NUMBER() OVER (ORDER BY id) AS t1
FROM myTable) AS nU WHERE t1 >= :offset";
$statement = $conn->prepare($sql);
$statement->bindParam(':top', $top, PDO::PARAM_INT);
$statement->bindParam(':offset', $offset, PDO::PARAM_INT);
$statement->execute();
return $statement->fetchAll();
} catch (Exception $e) {
echo $e->getMessage();
}
}
It's not allowed to use parameter bindings in PDO for SELECT and FROM part of a sql query. 不允许在PDO中将参数绑定用于sql查询的SELECT和FROM部分。
I replaced the whole query with another one where I don't have to set TOP 我将整个查询替换为另一个无需设置TOP的查询
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.