自动增加从数据库获得的VARCHAR值?

时间:2017-09-21 11:46:23

标签: php mysql

我从DB获取DRSYSCODE的值,现在我需要在插入时自动增加值

现在插入此格式MOB000571的值我需要增加到MOB000572,为此我使用下面的代码但是无法实现它,作为回报我只得到1的值,请帮助我在这个< / p>

$sql1="SELECT DRSYSCODE FROM DOCTORDETAILS  ORDER BY DRSYSCODE DESC LIMIT 1";
    $query=mysql_query($sql1);
    if (!$sql1) { // add this check.
    die('Invalid query: ' . mysql_error());
    }
    $output_array2=array();
    while($row=mysql_fetch_assoc($query))
    {
    $ids=$row['DRSYSCODE'];

    }
    echo $ids;
    if($ids){
        $su=1;
        echo $num =$ids+$su;
        $unique=$num;
    }

    echo $unique;

4 个答案:

答案 0 :(得分:3)

试试这个,

$pieces = explode("MOB", $string);
$autoinc_add = 1+$pieces[1];
$your_latest_autoincrement_value = str_pad($autoinc_add, 6, '0', STR_PAD_LEFT);
echo $your_latest_autoincrement_value;

答案 1 :(得分:2)

而不是$num =$ids+$su;使用此:

$num = 'MOB' . str_pad($su + substr($ids, 3), 6, '0', STR_PAD_LEFT);

答案 2 :(得分:0)

您的问题是您尝试将1,一个整数添加到一串文本中。您需要将文本字符串分解为文本部分,将数字部分分解为两个单独的变量(除非&#39; MOB&#39;始终是前三个字符,或者除非总共有三个字符后跟六个字符DRSYSCODE中的数字)然后在数字部分加1,然后在插入之前再将它们连接在一起。例如,如果DRSYSCODE始终为AAAxxxxxx(&#39; A&#39;为字符且&#39; x&#39;为数字),您可以执行以下操作:

if($ids){
    $alpha = substr($ids, 0, 3); // Get the first three characters and put them in $alpha
    $numeric = substr($ids, 3, 6); // Get the following six digits and put them in $numeric
    $numeric++; // Add one to $numeric
    $numeric = str_pad($numeric, 6, '0', STR_PAD_LEFT); // Pad $numeric with leading zeros
    $newids = $alpha.$numeric; // Concatenate the two variables into $newids
    }

我希望这会有所帮助。我在您的代码中看到了其他可以简化的地方,但这不是您问题的一部分。祝你一切顺利。

答案 3 :(得分:0)

我认为你应该将你的id分成两部分,第一部分是字母(MOB,在这种情况下),第二部分是数字(000571),然后你应该能够在数字上加1然后连接字母和递增的数字。这是因为您尝试将1添加到字符串,而不是整数或浮点值。字符串仅用于字符,这意味着您无法对它们进行数学运算。

我会用这个

替换if(ids) {...}部分
if($ids){
    $su=1;
    $splitedid = preg_split('/(?<=[a-zA-z])(?=[0-9]+)/',$ids); //Split in chars and numbers
    $zeros = substr_count($splitedid[1], '0'); //Count the number of zeros before the number
    $num = $splitedid[1]+$su; //Add one to the number
    $unique = $splitedid[0]; //Set $unique as the chars (MOB in your case)
    for ($i=0; $i < $zeros; $i++) { //Add to $unique the zeros that were in front of the number
      $unique .= '0';
    }
    $unique .= $num; //Add the number (572 = 571 + 1) to $unique so $unique is 'MOB000572'
}

希望它有所帮助!