【发布时间】:2020-11-22 16:07:46
【问题描述】:
我在从表中检索主键时遇到问题。
我的表结构如下。
表中有一条记录:
id = 1
PlaceName = 'in the matrix'
直接使用以下SQL语句检索:
SELECT id
FROM rde_613949.dbo.PlaceNames
WHERE PlaceName = 'in the matrix';
我正在尝试使用以下方法检索此记录的id:
function GetPlaceNameId($locationName)
{
//returns the id of the location name, creating if required
$resource = sqlsrv_connect($this->Server,$this->ConnectionInfo);
$tsql = "SELECT id from rde_613949.dbo.PlaceNames where PlaceName = ?";
$options = array("Scrollable" => SQLSRV_CURSOR_KEYSET);
$stmt = sqlsrv_query($resource, $tsql, array($locationName), $options);
if ($stmt)
{
while($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC));
{
$recordFound = true;
$locationId = $row['id'];
return $locationId;
}
}
else
{
return $this -> AddPlaceToDatabase($locationName);
}
}
这个方法失败了
while($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC))
$row 返回为 null,这意味着 $location 也返回为 null。
我有另一个表,该表采用另一种方法,这种方法适用。唯一真正的区别是我没有返回有效的主键。
public function FindStudentRecord($studentId)
{
require_once("./Student.php");
$resource = sqlsrv_connect($this->Server,$this->ConnectionInfo);
$tsql = "select FirstName, LastName from rde_613949.dbo.Students where StudentId = ?";
$options = array("Scrollable" => SQLSRV_CURSOR_KEYSET);
$result = sqlsrv_query($resource, $tsql, array($studentId), $options);
while($row = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC))
{
$student = new Student($studentId, $row['FirstName'], $row['LastName']);
return $student;
}
return null; //no records found return null
}
请有人向我解释一下这种情况的不同之处,并建议我如何正确地做到这一点?
【问题讨论】:
-
PlaceName列的排序规则是什么?GetPlaceNameId('in the matrix')调用返回什么? -
我不知道如何为 collum 获取整理。但由于我从未设置过整理,所以它应该是默认设置。表和 collum 是使用以下代码创建的。
function CreatePlacesTable() { $createQuery = 'create table Places ( id INT IDENTITY(1,1) PRIMARY KEY NOT NULL, PlaceName varchar (200) NOT NULL )'; $query = sqlsrv_prepare($this->Resource, $createQuery); return sqlsrv_execute($query); }在回答您的第二个问题时,它给出了相同的结果
标签: php sql-server sqlsrv