duanmaduan1848
2015-04-17 22:11
浏览 353
已采纳

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

I am trying to get the id of the last record inserted in an mssql database using pdo via php. 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. 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. Unfortunately, the driver does not support the lastinsertid() function with this database. 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. Another user suggested:

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

But, that didn't yield any result.

图片转代码服务由CSDN问答提供 功能建议

我试图通过php使用pdo获取插入mssql数据库的最后一条记录的id。 我已经阅读了很多帖子,但仍然无法让这个简单的例子起作用,所以我转向你。 许多以前的答案只给出了SQL代码,但没有解释如何将其合并到PHP中。 老实说,我不认为这是重复的。 基本插入代码是:

  $ CustID =“a123”; 
 $ Name =“James”
 $ stmt =“
 INSERT INTO OrderHeader(
 
SustID)  ,
名称
)VALUES(
:CustID,
:名称
)“; 
 $ stmt = $ db-> prepare(stmt); 
 $ stmt-> bindParam(':CustID  ',$ CustID);  
 $ stmt-> bindParam(':Name',$ Name); 
 $ stmt-> execute(); 
   
 
 

我必须使用 PDO查询MSSQL数据库。 不幸的是,驱动程序不支持此数据库的lastinsertid()函数。 我已经阅读了一些解决方案,但需要更多帮助才能使它们正常工作。

这里的一篇文章建议使用SELECT SCOPE_IDENTITY(),但没有举例说明如何将其合并到 上面的基本插入代码。 另一位用户建议:

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

但是,这并没有产生任何结果。

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • douxianji6104 2015-04-18 03:52
    已采纳

    If your id column is named id you can use OUTPUT for returning the last inserted id value and do something like this:

        $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

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

    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题