dory4404 2014-11-04 06:07 采纳率: 0%
浏览 74
已采纳

如何在mysql中增加默认值

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.

  • 写回答

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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥30 自适应 LMS 算法实现 FIR 最佳维纳滤波器matlab方案
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动