gpt4 book ai didi

php - 如何增加mysql中的默认值

转载 作者:行者123 更新时间:2023-11-29 01:40:09 24 4
gpt4 key购买 nike

我在 mysql 表中有一个字段 (demo_field)(varchar)。我想用预定义的前缀增加这个字段值。例如,我的字段第一个值是 demo001。现在,每当插入新值时,我都想增加数字,如 demo002、demo003。我如何使用 PHP 执行此操作。

最佳答案

试试这个 -

//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);

另一种不计数的方式

$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);

希望这可以解决 count 的问题。

另一种具有字母数字字符串最大计数且无填充的解决方案 -

$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);

关于php - 如何增加mysql中的默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26728760/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com