garrickplaisted Posted December 19, 2012 Share Posted December 19, 2012 I need to insert a new row in to a table, then grab the ID of taht row and update another table. What I have is something like this: $sql="INSERT INTO leads (field1, field2) VALUES('$value1','$value2')"; $query = mysql_query($sql); $lastID = mysql_insert_id(); $update = "UPDATE contacts SET leadID = $lastID WHERE contactID = $contactID"; $updateQuery = mysql_query($update); Everything works fine.. except that it inserts duplicate rows into the leads table. I have tried putting the update query into an if statement and it did the samething(this was just to try "something"). If I remove $lastID = mysql_insert_id(); it inserts just one row but obviously does not update the contacts table. So I am pretty sure it has to to with mysql_insert_id(). I need it to update the contacts table with the new id of the row inserted into the leads table. Any ideas would be greatly appreciated. Quote Link to comment https://forums.phpfreaks.com/topic/272197-running-an-insert-query-grabbing-the-id-and-updating-another-table-with-id/ Share on other sites More sharing options...
requinix Posted December 19, 2012 Share Posted December 19, 2012 (edited) mysql_insert_id() by itself will not cause this problem. How about posting the rest of your code, and the real stuff this time? Edited December 19, 2012 by requinix Quote Link to comment https://forums.phpfreaks.com/topic/272197-running-an-insert-query-grabbing-the-id-and-updating-another-table-with-id/#findComment-1400479 Share on other sites More sharing options...
garrickplaisted Posted December 19, 2012 Author Share Posted December 19, 2012 (edited) Here it is, thanks! $leadSQL="INSERT INTO $leadsTable (leadName, leadStatus, leadDescription, leadOpportunity, leadSource, leadSourceDescription, id, leadSince, contactID) VALUES ('$_POST[leadName]', '$_POST[leadStatus]', '$_POST[leadDescription]', '$_POST[leadOpportunity]', '$_POST[leadSource]', '$_POST[leadSourceDescription]','$_POST[id]','$leadSince','$_POST[contactID]')"; $leadQuery = mysql_query($leadSQL); $lastLeadID = mysql_insert_id(); $updateContactSQL = "UPDATE $contactsTable SET leadID = $lastLeadID WHERE contactID = $_POST[contactID]"; $updateContactQuery = mysql_query($updateContactSQL); Edited December 19, 2012 by garrickplaisted Quote Link to comment https://forums.phpfreaks.com/topic/272197-running-an-insert-query-grabbing-the-id-and-updating-another-table-with-id/#findComment-1400485 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.