OK, so here is my scenario - you may disagree with what I'm attempting to do but I have my reasons. The user is able to upload various information to the database, I also want them to be able to upload a picture at the same time. Now for various reasons I want to store the image with the file name the ID number of the record I'm adding (I have an ID column as the primary which auto-increments). Obviously I would have to store the file extension in the database too. Now is there a way I can add the record and then know what ID was set so that I can save the image? I don't want to query and select the highest ID as that could go wrong if two people were to submit the form at the same time. Any ideas?
After running an insert in PHP, you can get the AUTO_INCREMENT
ID from $mysqli->insert_id
(where $mysqli is a MySQLi
connection object), $pdo->lastInsertId
(where $pdo is a PDO
connection object), or mysql_insert_id()
(if you're still using MySQL
, which you shouldn't be) without having to run another query.
LAST_INSERT_ID()
will give you the ID
that was auto-generated:
... returns a
BIGINT
(64-bit) value representing the first automatically generated value that was set for anAUTO_INCREMENT
column by the most recently executedINSERT
statement to affect such a column. For example, after inserting a row that generates anAUTO_INCREMENT
value, you can get the value like this:mysql> SELECT LAST_INSERT_ID(); -> 195