Question

If I submit something to a MySQL database and that object gets an automatic ID assigned, how can I submit data to another table that references this ID? If the first table auto increments the IDs for new records, I can make a call to get the max ID of that table after submission - but this seems pretty hacky and prone to errors should multiple users be on the same application.

Was it helpful?

Solution

Your post is a little unclear, but what I think you need is mysql_insert_id(), it will return the id of the last inserted row using mysql_query.

Example:

mysql_query("INSERT INTO `journal_post` (...) VALUES (...)"); //Insert proper code in ...
$pid = mysql_insert_id(); //Contains the ID of the just inserted journal_post
if (...) { //Some check to see if an image was attached
  mysql_query("INSERT INTO `img_details` (...) VALUES (...)");
}

If this is not what you meant, please provide a code sample to elaborate the problem.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top