Joel James
Joel James

Reputation: 1345

How to increment a default value in 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.

Upvotes: 2

Views: 437

Answers (3)

Sougata Bose
Sougata Bose

Reputation: 31749

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

Upvotes: 3

karthik kumar
karthik kumar

Reputation: 51

you have to use an INT field and translate it to whatever format you want at "select" time.

In MySQL we cannot use AutoIncrement for Varchar.

Upvotes: 0

lkxiaolou
lkxiaolou

Reputation: 11

//use PHP not mysql
$pre = 'demo';
$num = 0;
define('MAX', 100);
for($num = 0; $num < MAX; $num++)
{
    $pre_str = $pre . sprintf("%03d", $num);
    //insert here
}

Upvotes: 1

Related Questions