Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to get the id to be inserted in the database before insert

I'm using PDO with PostgreSQL in PHP.

I'll let my users uploads files.

I would like to add the record id to the saved image.

Is it possible to get (or reserve) the record id before insertion in the database.

I don't think this is possible just want to be sure.

like image 737
PeeHaa Avatar asked Oct 17 '25 04:10

PeeHaa


2 Answers

Yes it is, you should use postgres function nextval to fetch the next value in the sequence. Look the default value in your table's id column, it should contain a nextval call to the used sequence.

For example if the table looks something like this:

image_id bigint not null default nextval('image_image_id_seq'::regclass)
data bytea not null

You can call:

SELECT NEXTVAL('image_image_id_seq') ;

which will "reserve" the id for you to be used later on:

INSERT INTO image (image_id, data) VALUES (?, ?) ;
like image 154
Mika Tähtinen Avatar answered Oct 18 '25 17:10

Mika Tähtinen


You can also do this :

BEGIN
INSERT RETURNING
get id
rename file
COMMIT
like image 37
bobflux Avatar answered Oct 18 '25 18:10

bobflux



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!