We help IT Professionals succeed at work.

We've partnered with Certified Experts, Carl Webster and Richard Faulkner, to bring you two Citrix podcasts. Learn about 2020 trends and get answers to your biggest Citrix questions!Listen Now

x

get @@identity of last inserted id with out using mssql built in functions

pjordanna
pjordanna asked
on
Medium Priority
1,158 Views
Last Modified: 2012-05-06
Hi I am trying to get the indentitiy back of the last inserted id, I am having issues installing the mssql extension and need an alternative without using the mssql built in functions. Can any one help? My example code is below. Thanks
<?php
$conn = new COM ("ADODB.Connection") or die("Cannot start ADO");
 
$connStr = "Provider=SQLOLEDB;User ID=****;Password=****;Initial Catalog=****;Data Source=****";
 
$conn->open($connStr);
$query = "SET NOCOUNT ON INSERT INTO 
			carhire_orders(
			BookingID,
			OrderDate) 
		VALUES(
			'$bookingID',
			'$orderDate') SELECT @@IDENTITY AS NewID SET NOCOUNT OFF";
 
$conn->execute($query);
 
// echo last inserted id
 
$conn->Close();
 
$conn = null;
?>

Open in new window

Comment
Watch Question

Guy Hengel [angelIII / a3]Billing Engineer
CERTIFIED EXPERT
Most Valuable Expert 2014
Top Expert 2009

Commented:
you should use

SELECT SCOPE_IDENTITY() as [NewID]

instead of

SELECT @@IDENTITY AS NewID

(unless you use sql 7...)

anyhow, what problems do you actually run into?

Author

Commented:
Hi thanks for you reply, but I sorted it.

$conn->execute($query);
 
echo $rs->Fields(0); // this was the part i was stuck on for some reason...

Open in new window

Billing Engineer
CERTIFIED EXPERT
Most Valuable Expert 2014
Top Expert 2009
Commented:
anyhow: use scope_identity() instead of @@identity, please.
the day your table get's a trigger that does a insert on his turn in to a table with identity field, @@identity will return the id value of that table and not your table...

Not the solution you were looking for? Getting a personalized solution is easy.

Ask the Experts
Access more of Experts Exchange with a free account
Thanks for using Experts Exchange.

Create a free account to continue.

Limited access with a free account allows you to:

  • View three pieces of content (articles, solutions, posts, and videos)
  • Ask the experts questions (counted toward content limit)
  • Customize your dashboard and profile

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.