I have a PHP script that creates an entry in the mysql database. PHP inserts all 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 related. Is there a way to get PHP to create an entry in one table in mysql, then find out the value of the incremental primary key from this first table so that it can insert mysql into the second table as a reference?
Yes. This is certainly doable. The function / method that you use to get the automatically added value that was just inserted will depend on how you access MySQL from PHP. If you use functions mysql_, use mysql_insert_id(). If you use functions mysqli_(or OO versions), use mysqli_insert_id(). If you use PDO, use PDO::lastInsertId(). In all cases, the function delegates to the MySQL function last_insert_id(), which is local to the connection, so you do not need to worry about parallel threads that interfere with each other.
mysql_
mysql_insert_id()
mysqli_
mysqli_insert_id()
PDO::lastInsertId()
last_insert_id()
To get the unique identifier inserted in the first table, you can use LAST_INSERT_ID()and save this as a link for your second table:
LAST_INSERT_ID()
SELECT LAST_INSERT_ID();
, . PHP mysql_insert_id, :)
mysql_insert_id
:
. . :
http://php.net/manual/en/function.mysql-insert-id.php