我有来自数据库的代码,数据应该按顺序自动出现。代码由文本和数字组成,如CO-00001
,但是当我生成代码时,它只在后面添加一个数字但不添加示例CO-00001 to CO-000001
的值如何解决它?
前:
$id = 0902340
$query = "SELECT substr(code_id,3,5) as cd FROM tb_inv WHERE substr(code_id,3,5) = '".$id."' ORDER BY code_id DESC LIMIT 1";
$get_id = $this->db->query($query);
$show_id = $get_id->num_rows();
$new_code = $get_id->row();
if($show_id > 0){
$new = $new_code->cd + 1;
$fix_code = $new;
}else{
$fix_code = 'CO-00001';
}
答案 0 :(得分:0)
你不能在字母表上做代数,因此你需要像这样分割字母和数字:
$id = 0902340
$query = "SELECT substr(code_id,3,5) as cd FROM tb_inv WHERE substr(code_id,3,5) = '".$id."' ORDER BY code_id DESC LIMIT 1";
$get_id = $this->db->query($query);
$show_id = $get_id->num_rows();
$new_code = $get_id->row();
if($show_id > 0){
$prefix = substr($new_code->cd, 0, 3); // get the prefix 3 chars at front
$number = substr($new_code->cd, 3); // get the remaining chars
$new = $number + 1; // add it with 1, php automatically convert strings that can be converted to numbers
$fix_code = $prefix . substr("00000" . $number, -5); // re-assemble the code
}else{
$fix_code = 'CO-00001';
}
答案 1 :(得分:0)
你可以将id分成两个部分,一个是字符串,另一个是数字。然后递增数字部分然后重新连接两部分
list($strPrefix, $digitPart) = split('-', $oldId);
$digitPart++;
$newCode = $strPrefix . '-' . $digitPart;