【发布时间】:2020-11-20 16:22:10
【问题描述】:
我有一个方法,它基于一个整数数组来选择记录,该数组在专门输入时有效。但是,当我尝试用从方法参数sqlsrv_query() 传入的数组替换该数组时,返回false。我确信这是非常简单的事情,但对我来说“明显”的可能性不起作用。
工作版
public function FindLocationRecords($locationIds)
{
require("./Location.php");
$resource = sqlsrv_connect($this->Server,$this->ConnectionInfo);
$tsql = "select Date, PlaceName from rde_613949.dbo.Locations where id in (14, 15, 16, 17); SELECT SCOPE_IDENTITY() as id";
$results = sqlsrv_query($resource, $tsql);
$locations = array();
while($row = sqlsrv_fetch_array($results, SQLSRV_FETCH_ASSOC))
{
$location = new Location($row['Date'], $row['PlaceName']);
array_push($locations, $location);
}
return $locations;
}
版本 1 不工作
public function FindLocationRecords($locationIds)
{
require("./Location.php");
$resource = sqlsrv_connect($this->Server,$this->ConnectionInfo);
$tsql = "select Date, PlaceName from rde_613949.dbo.Locations where id in ?; SELECT SCOPE_IDENTITY() as id";
$results = sqlsrv_query($resource, $tsql, array($locationIds));
$locations = array();
while($row = sqlsrv_fetch_array($results, SQLSRV_FETCH_ASSOC))
{
$location = new Location($row['Date'], $row['PlaceName']);
array_push($locations, $location);
}
return $locations;
}
第 2 版不工作
public function FindLocationRecords($locationIds)
{
require("./Location.php");
$resource = sqlsrv_connect($this->Server,$this->ConnectionInfo);
$tsql = "select Date, PlaceName from rde_613949.dbo.Locations where id in (?); SELECT SCOPE_IDENTITY() as id";
$results = sqlsrv_query($resource, $tsql, array($locationIds));
$locations = array();
while($row = sqlsrv_fetch_array($results, SQLSRV_FETCH_ASSOC))
{
$location = new Location($row['Date'], $row['PlaceName']);
array_push($locations, $location);
}
return $locations;
}
版本 3 不工作
public function FindLocationRecords($locationIds)
{
require("./Location.php");
$resource = sqlsrv_connect($this->Server,$this->ConnectionInfo);
$tsql = "select Date, PlaceName from rde_613949.dbo.Locations where id in ?; SELECT SCOPE_IDENTITY() as id";
$results = sqlsrv_query($resource, $tsql, $locationIds);
$locations = array();
while($row = sqlsrv_fetch_array($results, SQLSRV_FETCH_ASSOC))
{
$location = new Location($row['Date'], $row['PlaceName']);
array_push($locations, $location);
}
return $locations;
}
【问题讨论】:
-
您需要有类似
where id in (?, ?, ?);的 SQL,其 ? 的数量与您要检查的值相同。 -
如果我错了,请纠正我,但我认为如果我想做类似 'where field1 = ?, where friend2=?等等。我怎样才能使它适用于未知大小的数组?我需要将大量搜索传递给数据库吗?确定不是?
-
它反映了与mysql相同的方法(如stackoverflow.com/questions/3703180/…所示)。
-
为什么要执行
SELECT SCOPE_IDENTITY() as id? -
Raw SQL 并没有真正的列表或数组的概念。您可以按照建议实现自己的纯 PHP 解析或使用原始 SQL Server 参数。
标签: php sql-server sqlsrv