0

I have two tables Production and Production_Detail. Production_Detail holds details of some order and has a foreign key to Production. When I insert a row into Production, auto-incrementing column sets the key for that row. I need that key so that it can be linked with the new Production_Detail rows that will be inserted after inserting the master row in Production.

Using php, I insert the data:

insert into Production Values ('','$producer_id','$order_date','$company_id','$emp_id');

I need to find that '' part so that it can be used for later quires.

phs
  • 10,687
  • 4
  • 58
  • 84
Namit
  • 1,314
  • 8
  • 20
  • 36

4 Answers4

0

If you use PDO you can use the function

$id = $pdo->lastInsertId();
romainberger
  • 4,563
  • 2
  • 35
  • 51
  • but what if there are multiple users using that script? won't it result in a conflict? – Namit Feb 26 '12 at 21:05
  • No. I don't know the exact way to explain that, but it will give you the id of the query just above, because it's the same "connection" to the data base. Maybe somebody else can explain precisely. – romainberger Feb 26 '12 at 21:08
  • Thanks! I read the description and it says that it opens a connection with the `mysql_connect()`. – Namit Feb 26 '12 at 21:10
  • 1
    Also a dupe http://stackoverflow.com/questions/9315200/is-it-possible-for-mysqli-insert-id-to-return-an-incorrect-id-in-high-traffic-ap – Mike B Feb 26 '12 at 21:11
  • If you use `mysql_connect()`, you need to use mysql_insert_id(), like somebody else said. the `lastInsertId()` works if you use the PDO extension – romainberger Feb 26 '12 at 21:11
0

In depends what mysql/query extension you're using, but PHP has a mysql_insert_id function to return the auto increment value for the most recently inserted row.

pjumble
  • 16,880
  • 6
  • 43
  • 51
0

Depending on how you are using the database you may have to pass the database variable.

mysql

$last_id = mysql_insert_id($db);

mysqli

$last_id = mysqli_insert_id($db);
MattP
  • 2,798
  • 2
  • 31
  • 42