[英]MYSQL - Find the ID of the record just added
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).
现在出于各种原因,我想用文件名存储图像我正在添加的记录的ID号(我有一个ID列作为主要的自动递增)。 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?
现在有一种方法可以添加记录,然后知道设置了什么ID,以便我可以保存图像? 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.
我不想查询并选择最高ID,因为如果两个人同时提交表单可能会出错。 Any ideas?
有任何想法吗?
LAST_INSERT_ID()
will give you the ID
that was auto-generated: LAST_INSERT_ID()
将为您提供自动生成的ID
:
... 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....返回一个
BIGINT
(64位)值,表示由最近执行的INSERT
语句为AUTO_INCREMENT
列设置的第一个自动生成的值,以影响此类列。 For example, after inserting a row that generates anAUTO_INCREMENT
value, you can get the value like this:例如,在插入生成
AUTO_INCREMENT
值的行后,您可以获得如下值:mysql> SELECT LAST_INSERT_ID(); -> 195
在PHP中运行插入后,您可以从$mysqli->insert_id
(其中$ mysqli是MySQLi
连接对象), $pdo->lastInsertId
(其中$ pdo是PDO
连接对象)或mysql_insert_id()
获取AUTO_INCREMENT
ID (如果你还在使用MySQL
,你不应该这样做)而不必运行另一个查询。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.