I have a PHP script that creates an entry into a mysql database. The PHP inserts all of the data except the primary key, which mysql automatically increments. The problem is that i want to insert information into two tables, and these tables must be able to associate. Is there a way to have PHP create an entry in one table in mysql, then figure out the incremental primary key value from that first table, in order for it to insert into the second mysql table as a reference?
Share
Yes. This is certainly doable. The function/method you use to get the auto-incremented value that was just inserted will depend on the way you access MySQL from PHP. If you’re using the
mysql_functions, usemysql_insert_id(). If you’re using themysqli_functions (or OO versions), usemysqli_insert_id(). If you’re using PDO, usePDO::lastInsertId(). In all cases, the function delegates to the MySQL functionlast_insert_id()which is local to the connection so you need not worry about concurrent threads interfering with each other.