自动生成的序列号从001开始(仅适用于3个DIGITS) - PHP / MYSQL

时间:2013-11-29 10:23:06

标签: php mysql numbers sequence

我需要自动生成的序列号从001开始仅用于PHP / MYSQL中的3个DIGITS

ex:001接​​下来将是002,接下来将是003 ... 009 .. 010 ..119..120..etc但生成的数字应该是顺序而不是像001然后是120或008等,我需要在序号中。

实际上我有产品跟踪系统。我需要我的主要产品ID +自动序列号的混音器(如果需要,只能改变3位数)因此我的最终产品ID变为:

111-001,111-002,111-003,111-004 ....等

注意:这个自动序列号将插入我的mysql数据库中(在ADD按钮跟随Update查询之后(因此我的自动序列将在带有Update查询的数据库中输入))

3 个答案:

答案 0 :(得分:2)

只需将长度3和zerofill添加到您的id列。

ALTER TABLE  `YOUR_TABLE` CHANGE  
`id_column`  `id_column` INT( 3 ) UNSIGNED ZEROFILL NOT NULL AUTO_INCREMENT

答案 1 :(得分:0)

这应该适合您,只需稍加修改即可满足您的要求

 <?php
$connection = mysql_connect("localhost","root","")
or die("no connection");
$db_select=mysql_select_db("test",$connection)
or die("no connection to db");
$query3 = "SELECT * FROM simple";
$result3 = mysql_query($query3);
$count = mysql_num_rows($result3);
if($count == 0)
{
$seq = 1;
$ref = 111;
$a = sprintf("%04d", $seq);
$emp_id = $ref.'-'.$a;
$query= "INSERT INTO simple (emp_id) VALUES ('$emp_id')";
$result=mysql_query($query)or die(mysql_error());
}
else
{
    $query2 = "SELECT * FROM simple ORDER BY id DESC LIMIT 1";
    $result2 = mysql_query($query2);
    $row = mysql_fetch_array($result2);
    $last_id = $row['emp_id'];
    $rest = substr("$last_id", -4);  
    $insert_id = "$rest" + 1;
    echo $ars = sprintf("%04d", $insert_id);
    $ref = 111;
    $emp_id = $ref.'-'.$ars;
    $query= "INSERT INTO simple (emp_id) VALUES ('$emp_id')";
    $result=mysql_query($query)or die(mysql_error());
}

答案 2 :(得分:0)

试试这段代码:

$maxDigit=5; //maximum digit of ur number
$currentNumber=0020;  //example this is your last number in database all we need to do is remove the zero before the number . i dont know how to remove it
$count=strlen($currentNumber); //count the digit of number. example we already removed the zero before the number. the answer here is 2
$numZero="";
for($count;$count<=$maxDigit;$count++)
     $numZero=$numZero+"0";

$newNum=$newNum+$currentNumber;

输出:00020