简体   繁体   English

使用PDO和PHP从MSSQL表中获取最后插入的记录的ID

[英]Getting the id of the last inserted record from an MSSQL table using PDO and PHP

I am trying to get the id of the last record inserted in an mssql database using pdo via php. 我试图通过php通过pdo获取插入mssql数据库中的最后一条记录的ID。 I HAVE read many posts, but still can't get this simple example to work, so I am turning to you. 我已经阅读了许多帖子,但仍然无法使这个简单的示例正常工作,因此我转向您。 Many of the previous answers only give the SQL code, but don't explain how to incorporate that into the PHP. 先前的许多答案仅给出了SQL代码,但没有说明如何将其合并到PHP中。 I honestly don't think this is a duplicate. 老实说,我不认为这是重复的。 The basic insert code is: 基本插入代码为:

$CustID = "a123";
$Name="James"
$stmt = "
        INSERT INTO OrderHeader (
            CustID, 
            Name 
        ) VALUES (
            :CustID, 
            :Name
        )";
        $stmt = $db->prepare( stmt  );
        $stmt->bindParam(':CustID', $CustID);       
        $stmt->bindParam(':Name', $Name);
        $stmt->execute();

I have to use PDO querying an MSSQL database. 我必须使用PDO查询MSSQL数据库。 Unfortunately, the driver does not support the lastinsertid() function with this database. 不幸的是,驱动程序不支持此数据库的lastinsertid()函数。 I've read some solutions, but need more help in getting them to work. 我已经阅读了一些解决方案,但需要更多帮助才能使其正常工作。

One post here suggests using SELECT SCOPE_IDENTITY(), but does not give an example of how incorporate this into the basic insert code above. 这里的一篇文章建议使用SELECT SCOPE_IDENTITY(),但没有给出如何将其合并到上面的基本插入代码中的示例。 Another user suggested: 另一个用户建议:

    $temp = $stmt->fetch(PDO::FETCH_ASSOC);

But, that didn't yield any result. 但是,这没有产生任何结果。

If your id column is named id you can use OUTPUT for returning the last inserted id value and do something like this: 如果您的id列名为id ,则可以使用OUTPUT返回最后插入的id值,并执行以下操作:

    $CustID = "a123";
    $Name="James"
    $stmt = "INSERT INTO OrderHeader (CustID, Name) 
             OUTPUT INSERTED.id
             VALUES (:CustID, :Name)";

    $stmt = $db->prepare( stmt  );
    $stmt->bindParam(':CustID', $CustID);       
    $stmt->bindParam(':Name', $Name);
    $stmt->execute();

    $result = $stmt->fetch(PDO::FETCH_ASSOC);
    echo $result["id"]; //This is the last inserted id returned by the insert query

Read more at: 阅读更多信息:

https://msdn.microsoft.com/en-us/library/ms177564.aspx https://msdn.microsoft.com/en-us/library/ms177564.aspx

http://php.net/manual/es/pdo.lastinsertid.php http://php.net/manual/es/pdo.lastinsertid.php

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

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