I have a field (demo_field)(varchar) in mysql table. I want to increment this field value with a pre defined prefix.
For example my field first value is demo001
. Now when ever new values inserted I want to increment the numeric numbers like demo002, demo003
.
How can I do this with PHP.
如何在mysql中增加默认值
- 写回答
- 好问题 0 提建议
- 追加酬金
- 关注问题
- 邀请回答
-
3条回答 默认 最新
- duanju9104 2014-11-04 06:26关注
try this -
//fetch data from table $sql = $mysqli->query('select count(demo_field) as total,demo_field from tablename limit 1'); $res = $sql->fetch_assoc(); //generate string from existing data $str = substr($res['demo_field'], 0, 4); $dig = str_replace($str, '', $res['demo_field']); $dig = $dig+$res['total']; //add padding if needed $dig = str_pad($dig, 3, '0', STR_PAD_LEFT); //concatenate string & digits $newStr = $str.$dig; var_dump($newStr);
Another way without count
$sql = $mysqli->query('select max(demo_field) as demo_field from demo'); $res = $sql->fetch_assoc(); $str = substr($res['demo_field'], 0, 4); $dig = str_replace($str, '', $res['demo_field']); $dig += 1; $dig = str_pad($dig, 3, '0', STR_PAD_LEFT); $newStr = $str.$dig; var_dump($newStr);
hope this might solve the problem with
count
.another solution with max count for alphanumeric string and without padding -
$sql = $mysqli->query('select max(cast(substring(demo_field, 5) as unsigned)) as digit, demo_field from demo'); $res = $sql->fetch_assoc(); $str = substr($res['demo_field'], 0, 4); $dig = $res['digit'] + 1; $newStr = $str.$dig; var_dump($newStr);
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报
悬赏问题
- ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
- ¥20 cad图纸,chx-3六轴码垛机器人
- ¥15 移动摄像头专网需要解vlan
- ¥20 access多表提取相同字段数据并合并
- ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
- ¥20 Java-Oj-桌布的计算
- ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
- ¥20 有人知道这种图怎么画吗?
- ¥15 pyqt6如何引用qrc文件加载里面的的资源
- ¥15 安卓JNI项目使用lua上的问题