1

I need to use SELECT LAST_INSERT_ID() function of MySQL to get the ID of last inserted row. When I try to run this:-

  mysql_query("
    INSERT INTO `posts`
           (`user`, `body`, `time`, `pageID`)
           VALUES('pachykutty', 'testMessage', '2012-10-26 04:59:43', 1);
    SELECT LAST_INSERT_ID();");

Gives me error, but When I run the two queries separately like this:-

mysql_query("
INSERT INTO `posts`
       (`user`, `body`, `time`, `pageID`)
       VALUES('pachykutty', 'testMessage', '2012-10-26 04:59:43', 1)");
mysql_query("SELECT LAST_INSERT_ID()");

It is OK. I fear that If two clients ran the query same time, their LAST_INSERT_ID will conflict. So I want to run the two queries together without delay. Is there any way?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
itsfarseen
  • 1,109
  • 10
  • 25

1 Answers1

3

You can use query like that

mysql_query("
INSERT INTO `posts`
       (`user`, `body`, `time`, `pageID`)
       VALUES('pachykutty', 'testMessage', '2012-10-26 04:59:43', 1)");
$var =  mysql_insert_id();

mysql_insert_id acts on the last performed query.

So no worries and use above code.

Lalit Jain
  • 138
  • 7
  • Thank you very much for the info. But one doubt. I have on actions.php – itsfarseen Oct 29 '12 at 15:47
  • 1
    Thank you very much for the info. But one doubt. I have on actions.php in which scripts.php is included. Scripts.php contains function like insertPost($user,$body,$page); which will automatically do validation of data. All posted data is sent to actions.php and insertPost function is called. If i call mysql_insert_id() in actions.php - neither in insertPost() function nor inside scripts.php - Can I still get the correct value,no conflicts with other users? – itsfarseen Oct 29 '12 at 15:51