【问题标题】:Php sqlsrv_query & sqlsrv_fetch_array used on primary key with Microsoft SQL Server用于 Microsoft SQL Server 主键的 PHP sqlsrv_query 和 sqlsrv_fetch_array
【发布时间】: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


【解决方案1】:

虽然我不明白为什么我通过选择 * 而不是选择 id 来解决这个问题。如果有人明白这一点,请发帖提供建议。

【讨论】:

  • 一个可能的解释是数据库排序规则。您可以使用SELECT DATABASEPROPERTYEX('rde_613949', 'Collation') 检查排序规则。在区分大小写的排序规则的情况下,Idid 是不同的列名。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-29
  • 1970-01-01
  • 1970-01-01
  • 2013-02-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多