dsj60862 2014-07-01 15:53
浏览 112
已采纳

SELECT_IDENTITY()无法在php中工作

Scenario:

I have a SQL Query INSERT INTO dbo.Grades (Name, Capacity, SpringPressure) VALUES ('{PHP}',{PHP}, {PHP})

The data types are correct.

I need to now get the latest IDENTIY which is GradeID.

I have tried the following after consulting MSDN and StackOverflow:

  • SELECT SCOPE_IDENTITY() which works in SQL Management Studio but does not in my php code. (Which is at the bottom), I have also tried to add GO in between the two 'parts' - if I can call them that - but still to no avail.
  • The next thing I tried, SELECT @@IDENTITY Still to no avail.
  • Lastly, I tried PDO::lastInsertId() which did not seem to work.

What I need it for is mapping a temporary ID I assign to the object to a new permanent ID I get back from the database to refer to when I insert an object that is depended on that newly inserted object.

Expected Results:

Just to return the newly inserted row's IDENTITY.

Current Results:

It returns it but is NULL.

[Object]
    0: Object
       ID: null

This piece pasted above is the result from print json_encode($newID); as shown below.

Notes,

This piece of code is running in a file called save_grades.php which is called from a ajax call. The call is working, it is just not working as expected.

As always, I am always willing to learn, please feel free to give advice and or criticize my thinking. Thanks

Code:

for ($i=0; $i < sizeof($grades); $i++) { 
     $grade = $grades[$i];

     $oldID = $grade->GradeID;
     $query = "INSERT INTO dbo.Grades (Name, Capacity, SpringPressure) VALUES ('" . $grade->Name . "',". $grade->Capacity .", ".$grade->SpringPressure .")";

     try {
        $sqlObject->executeNonQuery($query);
        $query =  "SELECT SCOPE_IDENTITY() AS ID";
        $newID = $sqlObject->executeQuery($query);
        print json_encode($newID);
     } catch(Exception $e) {
        print json_encode($e);
     }


     $gradesDictionary[] = $oldID => $newID;

}

EDIT #1

Here is the code for my custom wrapper. (Working with getting the lastInsertId())

class MSSQLConnection
    {
            private $connection;
            private $statement;
            public function __construct(){
                    $connection = null;
                    $statement =null;
            }

            public function createConnection() {

                    $serverName = "localhost\MSSQL2014";
                    $database = "{Fill In}";
                    $userName = "{Fill In}";
                    $passWord = "{Fill In}";

                    try {
                       $this->connection = new PDO( "sqlsrv:server=$serverName;Database=$database", $userName, $passWord);
                       $this->connection->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
                    }
                    catch( PDOException $e ) {
                       die("Connection Failed, please contact system administrator.");
                    }

                    if ($this->connection == null) {
                            die("Connection Failed, please contact system administrator.");
                    }
            }

            public function executeQuery($queryString) {
                    $results = array();
                    $this->statement = $this->connection->query( $queryString );
                    while ( $row = $this->statement->fetch( PDO::FETCH_ASSOC ) ){
                       array_push($results, $row);
                    }
                    return $results;
            }

    public function executeNonQuery($queryString) {
                    $numRows = $this->connection->exec($queryString);
            }

            public function getLastInsertedID() {
                    return $this->connection->lastInsertId();
            }

            public function closeConnection() {
                    $this->connection = null;
                    $this->statement = null;
            }
    }
  • 写回答

2条回答 默认 最新

  • doushouj966020 2014-07-01 19:20
    关注

    This is PDO right ? better drop these custom function wrapper...

    $json = array();
    
    for ($i=0; $i < sizeof($grades); $i++) { 
        //Query DB
        $grade = $grades[$i];   
        $query = "INSERT INTO dbo.Grades (Name, Capacity, SpringPressure) 
                  VALUES (?, ?, ?)";
    
        $stmt = $conn->prepare($query);
        $success = $stmt->execute(array($grade->Name,
                                        $grade->Capacity,
                                        $grade->SpringPressure));
    
        //Get Ids
        $newId = $conn->lastInsertId();
        $oldId = $grade->GradeID;
    
        //build JSON
        if($success){
            $json[] = array('success'=> True,
                            'oldId'=>$oldId, 'newId'=>$newId);
        }else{
            $json[] = array('success'=> False,
                            'oldId'=>$oldId);
        }
    }
    print json_encode($json);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 基于双目测规则物体尺寸
  • ¥15 wegame打不开英雄联盟
  • ¥15 公司的电脑,win10系统自带远程协助,访问家里个人电脑,提示出现内部错误,各种常规的设置都已经尝试,感觉公司对此功能进行了限制(我们是集团公司)
  • ¥15 救!ENVI5.6深度学习初始化模型报错怎么办?
  • ¥30 eclipse开启服务后,网页无法打开
  • ¥30 雷达辐射源信号参考模型
  • ¥15 html+css+js如何实现这样子的效果?
  • ¥15 STM32单片机自主设计
  • ¥15 如何在node.js中或者java中给wav格式的音频编码成sil格式呢
  • ¥15 不小心不正规的开发公司导致不给我们y码,