galvin Posted July 15, 2010 Share Posted July 15, 2010 Not sure if this is more of a PHP question or MySQL, so putting it here (feel free to move it if it should be). I have code where I am inserting data into a MySQL database and a field called "userid" gets added using the auto-increment feature. So if the last userid in the table was "17", then the next userid would get populated with "18". Now, right after i insert the user info, I want to retrieve that "userid" value (i.e. "18" in my example). For some reason I'm stuck on how to do this. See example below... $sql = "INSERT into users (firstname, lastname, email) values ('{$_POST['firstname']}, '{$_POST['lastname']}, '{$_POST['email']}')"; $adduser = mysql_query($sql, $connection); if (!$adduser) { die("Database query failed: " . mysql_error()); } else { $success = "Success! User was added!"; ***RIGHT HERE, I WANT TO SOMEHOW RETRIEVE THE NEWLY ADDED USERID VALUE FOR THE USER I JUST INSERTED ABOVE. HOW!?!?*** } My first thought was to do a MySQL query where I grab the userid from the last inserted record, but if my application has many users being inserted at the same time, I feel like that has potential to bring back the wrong userid. Anyone have any ideas? Link to comment https://forums.phpfreaks.com/topic/207785-how-to-retrieve-value-from-mysql-table-immediately-after-it-was-inserted/ Share on other sites More sharing options...
Pikachu2000 Posted July 15, 2010 Share Posted July 15, 2010 Assuming you have an auto-incremented field, mysql_insert_id() should be what you need. Link to comment https://forums.phpfreaks.com/topic/207785-how-to-retrieve-value-from-mysql-table-immediately-after-it-was-inserted/#findComment-1086202 Share on other sites More sharing options...
galvin Posted July 15, 2010 Author Share Posted July 15, 2010 Beautiful, exactly what I needed! Thanks a lot Pikachu!!! Link to comment https://forums.phpfreaks.com/topic/207785-how-to-retrieve-value-from-mysql-table-immediately-after-it-was-inserted/#findComment-1086206 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.