Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(mysql, php) How to get auto_increment field value before inserting data?

Tags:

php

mysql

I'm uploading image file to storage server. Before uploading I should compose filename, which contains AUTOINCREMENT VALUE in it (for example, 12345_filename.jpg).

How could I get autoincrement value before inserting into DB?

I see only one solution

  1. insert empty row
  2. get it's autoincrement value
  3. delete this row
  4. insert row with real data using autoincrement value from p.1

Is there any other solutions?

Thank you

like image 648
Kirzilla Avatar asked Feb 12 '10 11:02

Kirzilla


People also ask

How can I get auto increment value after insert?

To obtain the value immediately after an INSERT , use a SELECT query with the LAST_INSERT_ID() function. For example, using Connector/ODBC you would execute two separate statements, the INSERT statement and the SELECT query to obtain the auto-increment value.

How do I get next auto generated value in SQL?

MySQL has the AUTO_INCREMENT keyword to perform auto-increment. The starting value for AUTO_INCREMENT is 1, which is the default. It will get increment by 1 for each new record. To get the next auto increment id in MySQL, we can use the function last_insert_id() from MySQL or auto_increment with SELECT.

How do you set a field as auto increment in MySQL?

In MySQL, the syntax to change the starting value for an AUTO_INCREMENT column using the ALTER TABLE statement is: ALTER TABLE table_name AUTO_INCREMENT = start_value; table_name.

Why does auto increment jumps by more than the number of rows inserted?

It could have multiple causes: Check if the auto_increment value on the table itself, has the next highest value. Mind that if you have transactions where you INSERT a row and rollback the transaction, that auto_increment value will be gone/skipped.


1 Answers

If you are using PDO, here is a "single line" solution :

$nextId = $db->query("SHOW TABLE STATUS LIKE 'tablename'")->fetch(PDO::FETCH_ASSOC)['Auto_increment'];

where tablename is replaced by your table.

like image 169
Meloman Avatar answered Sep 28 '22 02:09

Meloman