简体   繁体   English

如何为PHP MySQL驱动数据库生成下一个ID号

[英]How generate next id number for php mysql driven database

I have a table employees which contains the details of employees in a firm. 我有一个employees表,其中包含公司雇员的详细信息。

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. 例如,数据库包含12名员工。 The serial number of the last entry is 12 . 最后一个条目的序列号是12 When I try to add new employee it should automatically assign the serial number 13 . 当我尝试添加新员工时,它应该自动分配序列号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). 即使查询当前数据库状态(除了正好有一个用户正在使用该应用程序),您也无法精确预测下一个auto_increment ID。 Example: you open the form, fetch the next auto_increment ID from the DB and display 13 as the next predicted value. 示例:打开表单,从数据库中获取下一个auto_increment ID,并显示13作为下一个预测值。 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. 另一个用户记录的真实ID为13,即您的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). 如果您确实要在表单中显示使用的ID,则需要对记录进行某种分配(例如,在打开表单并使用其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, ...). 唯一的缺点是,如果用户未填写表格(例如14、15、18、20,...)而打开表格,它可能会给您提供不连续的ID。

If the serial number is set to auto_increment you could look up the next auto_increment value beforehand using: 如果序列号设置为auto_increment,则可以使用以下命令预先查找下一个auto_increment值:

$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. 其中table_name是表的名称。

Set the serial ID to AUTO_INCREMENT 将序列号设置为AUTO_INCREMENT

Check it out 看看这个

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

for employee_id use auto increment

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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