开发者

How to get the primary key which is an auto-increment for the row just entered in PHP?

开发者 https://www.devze.com 2023-04-06 14:34 出处:网络
I have a SQL query like $result = mssql_query(\"INSERT into CALLER ( status, media, media_2, first_name, last_name,street_address, city,

I have a SQL query like

$result = mssql_query("INSERT into CALLER
  ( status, media, media_2, first_name, last_name,  street_address, city,
  state, zipcode, home_phone_no, mobile_phone_no,email, probl开发者_C百科em, 
  medical_condition, comments,  updated_date )
  VALUES    
  ('CALL', '$media', '$media_2','$fname','$lname', '$street_addr', '$city',
  $state','$zip', '$phone_alt', '$phone','$email','$problem','$mc',
  '$comments',GetDate() ); ");

The primary key for the table CALLER is an auto-increment. How can I get the Primary Key of the row just inserted after this query ?


Correction: use this.

$query = mssql_query("SELECT @@IDENTITY");
$row   = mssql_fetch_assoc($query);


Well if you have any CANDIDATE KEY in the table, you can use that to retrieve the last inserted row.

Say you have a candidate key consisting of columns status, email and problem.

Then you can execute a query like this just after your insert.

$query = "SELECT id FROM CALLER 
          WHERE 
               status = '" . $status . "' 
               AND email = '" . $email . "' AND 
               problem = '" . $problem . "'";
mssql_query($query);

This will return the id for that entry.

Update
I just saw this in a comment by Mikael to Femi's Answer, you can use SCOPE_IDENTITY()

It returns the las insert id for the current connection in current scope. So it should work for you even if multiple instances do inserts which are interleaved.

So you can simply do this after the insert

$res = mssql_query('SELECT SCOPE_IDENTITY()');
0

精彩评论

暂无评论...
验证码 换一张
取 消