简体   繁体   中英

How generate next id number for php mysql driven database

I have a table employees which contains the details of employees in a firm.

Each one assigned a unique serial number. Whenever we add a new employee, it should display a serial number in adding form, which is one number greater than the serial number of the last entered employee.

For example, the database contains 12 employees. The serial number of the last entry is 12 . When I try to add new employee it should automatically assign the serial number 13 . So I don't need to enter serial number. How can I do this?

You can't precisely predict the next auto_increment ID, even when querying the current database status (apart from exactly one user is using the application). Example: you open the form, fetch the next auto_increment ID from the DB and display 13 as the next predicted value. In the meantime, another user opens the form and saves it faster than you. The real ID of the other user's record would be 13, yours 14.

If you really want to display the used ID in your form, you need to do some kind of allocation of your record (eg create an empty record on opening the form and using its ID). With some kind of status field or required field you could filter those empty records in your application until they are completed and periodically purge uncompleted records. Only downside is, that it will probably give you uncontinuous IDs if users open the form without completing it (eg 14, 15, 18, 20, ...).

If the serial number is set to auto_increment you could look up the next auto_increment value beforehand using:

$sql = "SHOW TABLE STATUS LIKE table_name";
$r = mysql_query($sql);

$row = mysql_fetch_assoc($r);
$next_increment = $row['Auto_increment'];

Where table_name is the name of your table.

Set the serial ID to AUTO_INCREMENT

Check it out

http://dev.mysql.com/doc/refman/5.0/en/example-auto-increment.html

for employee_id use auto increment

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM