Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve the ID of an inserted record: Php & MS SQL SERVER

This question relates to:

PHP Version 5.3.6

Microsoft Drivers for PHP for SQL Server

I am trying to properly retrieve the ID of a record insert using a combination of PHP and SQL Server 2005 or 2008.

This question assumes the existence of the following table:

CREATE TABLE users([id] [int] IDENTITY(1,2) NOT NULL,[username] [varchar](50) NOT NULL,[password] [varchar](40) NOT NULL,[first_name] [varchar](30) NOT NULL,[last_name] [varchar](30) NOT NULL)

If I were to run the following query in Management Studio or via ASP (Classic), a record would be inserted and an ID would be returned, but the same behavior does not seem to exist with PHP and this driver.

INSERT INTO users (username, password, first_name, last_name) VALUES ('x','x','x','x') ; SELECT @@IDENTITY ;

I need help figuring out how to properly pull an ID either by chaining SQL statements together or by any other method.

I have worked up some code.

Variation 1 is a simple select (via query) - no insertion or ID retrieveal performed

Variation 2 is a chained SQL statement which inserts the new record properly, but does not return the ID

Variation 3 uses (execute) instead of (query). The record is inserted, but the ID is not returned. This one generated an error because sqlsrv_execute returns true/false instead of a recordset.

So how can I modify my code to insert a record and retrive an ID? (I'm working on the assumption that the answer to this question will extend to Stored Procedures that return data as well, but perhaps that is not the case)

Thank you.

// Database connection
// -------------------------------------------------------------------------------------------------------
$conn = sqlsrv_connect(DB_SERVER,array("UID" => DB_USER, "PWD" => DB_PASSWORD, "Database"=> DB_NAME ));

// Variation 1, straight select
// -------------------------------------------------------------------------------------------------------
$sql = "SELECT * FROM users;";
$result = sqlsrv_query($conn,$sql);
$row = sqlsrv_fetch_array($result);

// Variation 2, Insert new record and select @@IDENTITY
// -------------------------------------------------------------------------------------------------------
$sql = "INSERT INTO users  (username, password, first_name, last_name) VALUES ('x','x','x','x')  ; SELECT @@IDENTITY ;";
$result = sqlsrv_query($conn,$sql);
$row = sqlsrv_fetch_array($result);

// Variation 3, using EXECUTE instead of QUERY
// -------------------------------------------------------------------------------------------------------
//$sql = "INSERT INTO users  (username, password, first_name, last_name) VALUES ('x','x','x','x')  ; SELECT @@IDENTITY as id ;";
$sql = "INSERT INTO users  (username, password, first_name, last_name) VALUES ('x','x','x','x')  ; SELECT SCOPE_IDENTITY() as id ;";

$stmt = sqlsrv_prepare( $conn, $sql);
$result = sqlsrv_execute($stmt);
$row = sqlsrv_fetch_array($result);
like image 531
Ralph M. Rivera Avatar asked Jul 27 '11 19:07

Ralph M. Rivera


People also ask

How do I get the inserted record ID in SQL?

SCOPE_IDENTITY() returns the last identity value generated for any table in the current session and the current scope. Generally what you want to use. IDENT_CURRENT('tableName') returns the last identity value generated for a specific table in any session and any scope.

What is mysqli_insert_id function in PHP?

The mysqli_insert_id() function returns the id (generated with AUTO_INCREMENT) from the last query.

How can I get last INSERT ID in PDO?

You can use PDO::lastInsertId() . @ArtGeigel It will be the last inserted ID of the connection underlying the PDO instance. In other words, it's safe in the scenario you described since concurrent queries would take place in separate connections.


3 Answers

http://www.php.net/manual/en/function.mssql-query.php#104263

I don't use MS SQL at all but have briefly read up on this. It would seem you need to make a call to sqlsrv_next_result. An example is provided in that comment:

$query = "INSERT INTO test (col1, col2) VALUES (?,?); SELECT SCOPE_IDENTITY()";
$resource=sqlsrv_query($conn, $query, $arrParams); 
sqlsrv_next_result($resource); 
sqlsrv_fetch($resource); 
echo sqlsrv_get_field($resource, 0); 
like image 116
Jonathon Avatar answered Oct 01 '22 15:10

Jonathon


First, do not use @@identity for this purpose if you value the integrity of your data as it can return the wrong answer. Even worse, it can work correctly for years before someone puts a trigger on the table and it starts quietly sending the wrong value.

Use the OUTPUT clause or Scope_identity().

Example of the SQL used to do the output clause:

DECLARE @MyTableVar table( myID int,
                           myName varchar(50),
                           ModifiedDate datetime);
INSERT dbo.mytable
    OUTPUT INSERTED.myID, INSERTED.myName, INSERTED.ModifiedDate
        INTO @MyTableVar
VALUES ('test', GETDATE());
like image 22
HLGEM Avatar answered Oct 01 '22 15:10

HLGEM


This works for me...

 $sql = "Insert into MyTable(column1,column2,column3) VALUES (? , ? , ?); SELECT @@IDENTITY as id;";
 $params = array($value1,$value2,$value3);
 $stmt = sqlsrv_query( $conn, $sql, $params);
 $next_result = sqlsrv_next_result($stmt); 
 $row = sqlsrv_fetch_array($stmt); 
 echo "ROW INSERTED WITH ID : " . $row["id"];
 if( $stmt === false ) {
 Echo "Error writing new application to table";
 }  
like image 24
John Avatar answered Oct 01 '22 16:10

John