This question relates to:
PHP version 5.3.6
Microsoft drivers for PHP for SQL Server
I am trying to get the record insert ID correctly 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 ran the following query in Management Studio or through ASP (classic), the record would be inserted and the identifier 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 correctly get the identifier, either by concatenating SQL statements, or in any other way.
I have processed some code.
Option 1 - this is a simple choice (through a query) - neither inserting nor re-executing the identifier is performed
Option 2 is an encoded SQL statement that correctly inserts a new record but does not return an identifier
Option 3 uses (executes) instead of (query). The record is inserted, but the identifier is not returned. This caused an error because sqlsrv_execute returns true / false instead of a recordset.
So, how can I change my code to insert a record and extract an identifier? (I am working on the fact that the answer to this question will apply to stored procedures that also return data, but maybe this is not so)
Thanks.
// 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);