Monday, June 16, 2008

How to get the MySql last inserted row using PHP?

When you use a auto increment primary key id field, you usually have no track of what is the current inserted id in the auto increment field. But there are situation where you need to know the last increamented id.
You can simply use mysql_insert_id()



<?php

mysql_query("insert into mytable (v_name) values ('kusal')");
$last_id = mysql_insert_id();

echo $last_id;

?>


Freelance Jobs

8 comments:

  1. Thank you very much for the code. Exactly what I needed!

    ReplyDelete
  2. thank you very much too

    wilson
    wilsonelec@gmail.com

    ReplyDelete
  3. Thanks, Thanks a lot, It is much easier in MySQl than MS SQl

    ReplyDelete
  4. of course, just do it:
    $last_id = mysql_insert_id();
    (without that last ")" that was given in the example)

    ReplyDelete
  5. Brilliant. Just what I wanted. Thanks for posting this.

    ReplyDelete
  6. If you insert more than 1 VALUE it returns only de first inserted ID :(
    ----------------------------------
    mysql_select_db($database_cnn_sis, $cnn_sis);
    $str = "INSERT INTO emails VALUES (NULL,2,'asd'),(NULL,2,'asd'),(NULL,2,'asd'),";
    $str = substr($str,0,(strlen($str)-1));
    $strLastID = mysql_query($str);
    $last_id = mysql_insert_id();
    echo $last_id.' -- '.mysql_info();

    //1 -- Records: 3 Duplicates: 0 Warnings: 0

    ReplyDelete
  7. Thank You Very Much....I just wanted this!

    ReplyDelete