使用PDO和PHP从MSSQL表中获取最后插入的记录的ID [英] Getting the id of the last inserted record from an MSSQL table using PDO and PHP

查看:215
本文介绍了使用PDO和PHP从MSSQL表中获取最后插入的记录的ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过php使用pdo获取插入到mssql数据库中的最后一条记录的ID.我已经阅读了许多帖子,但仍然无法使这个简单的示例正常工作,因此我转向您.先前的许多答案仅给出了SQL代码,但没有说明如何将其合并到PHP中.老实说,我不认为这是重复的.基本的插入代码是:

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();

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

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.

这里的一篇文章建议使用SELECT SCOPE_IDENTITY(),但没有给出如何将其合并到上面的基本插入代码中的示例.另一个用户建议:

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.

推荐答案

如果您的id列名为id,则可以使用OUTPUT返回最后插入的id值,并执行以下操作:

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

更多信息,请访问:

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

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

这篇关于使用PDO和PHP从MSSQL表中获取最后插入的记录的ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆