How to increment a default value in mysql - php

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.

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

//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
}

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.

Related

how to add string to the random generated number using php?

In my php code, while inserting new record, invoice number should be 0001. Here I want to add characters/a word(for example 'optical') and it should be like optical0001. How can I add this before the number?
$query = "select * from cust_report_invoices order by invoiceID desc limit 1";
$result = $link->query($query);
$row = $result->fetch_assoc();
$invoiceNo = $row['invoiceNo'];
$prefix = 'Baopt_';
$getinvoiceNo = $prefix . str_pad($invoiceNo + 1, 4, 0, STR_PAD_LEFT);
$sql = "INSERT INTO cust_report_invoices (invoiceNo,invoiceDate)
VALUES ('$getinvoiceNo', '$getinvoiceDate' )";
str_pad return string (doc). So just concat with .:
$prefix = 'optical';
$invoice = $prefix . str_pad($invoiceNo + 1, 4, 0, STR_PAD_LEFT);
Edit
When adding new element you need to cut the prefix out - you can use this:
$prefix = 'Baopt_';
$invoiceNo = $row['invoiceNo'];
if (substr($invoiceNo, 0, strlen($prefix)) == $prefix) // if already has prefix
$invoiceNo = substr($invoiceNo, strlen($prefix)); // remove it
$getinvoiceNo = $prefix . str_pad($invoiceNo + 1, 4, 0, STR_PAD_LEFT);
When working in PHP you can use the . as concatenation-operator. I see that you use the function str_pad that returns as string.
So you can just concat the prefix with the invoice number like this.
$prefix = 'optical';
$invoice = $prefix . str_pad($invoiceNo + 1, 4, 0, STR_PAD_LEFT);
$prefix can be anything you want.
When invoice = 0001 this example will return optical0001
Just "Opticals".$getinvoiceNo
Dot is concatenating strings.
Not sure if I understand correctly, you want to prepend "optical" to $getinvoiceNo?
If yes then it is simple,
invoiceId = "optical$getinvoiceNo"

Can not add automatic numbers behind with php

I have the code from the database, the data should appear automatically in sequence. the code is composed of text and number like this CO-00001 but when I generate the code it just adds one digit in the back but not add the value of example CO-00001 to CO-000001 how to solve it?
ex :
$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';
}
you can't do algebra on alphabets, therefore you need to split the alphabets and the numerics like so:
$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';
}
you can split the id into two parts, the string one, and the digit one. then increment the digit part then re concat the two parts again
list($strPrefix, $digitPart) = split('-', $oldId);
$digitPart++;
$newCode = $strPrefix . '-' . $digitPart;

Generate an id with fixed alpha numeric string and variable integer part php

I am trying to generate an id with fixed alphanumeric part and a varying 3 digit numeric part.
That is, the id will look like:
LAB-SER-420316-1415-000
LAB-SER-420316-1415-001
...
LAB-SER-420316-1415-010
LAB-SER-420316-1415-020
...
LAB-SER-420316-1415-110
LAB-SER-420316-1415-210
.....
My task is to generate this id's only once, that is repeating id has to be avoided. Also once the page is loaded, it should generate single id.This is like giving a bill number or something like that. I've created a function to generate this string upto a limit. But I need it to generate everytime the page is loaded.
Code:
<?php
function generatebillno()
{
$saved="LAB-SER-420316-1415-";
for($count = 0; $count <= 999; $count++)
{
$var= str_pad($count, 3, '0', STR_PAD_LEFT);
return $saved.$var;
}
}
echo generatebillno();
?>
Can anyone help me to do this. I am stuck here..
try this -
//fetch the max id (the last digit as number)
$sql = $mysqli->query('select max(cast(substring(demo_field, 21) as unsigned)) as digit,
demo_field from demo');
$res = $sql->fetch_assoc();
//check for empty valyues
if (empty($res['demo_field'])) {
$str = "LAB-SER-420316-1415";
$res['digit'] = 0;
} else {
$str = substr($res['demo_field'], 0, 19);
}
$dig = $res['digit'] + 1;
//add padding if needed
$dig= str_pad($dig, 3, '0', STR_PAD_LEFT);
$newStr = $str.'-'.$dig;
var_dump($newStr);

Generating a new unique alpha numeric string,

I need to generate an alpha numeric string and compare with database values but if the value is present in database then we should generate a different numeric string and again it should be compared with database values....
<?php
$character_array = array_merge(range('a', 'z'), range(0, 9));
$Emp_Id = "";
for($i = 0; $i < 6; $i++) {
$Emp_Id .= $character_array[rand(0, (count($character_array) - 1))];} ?>
which is working fine by creating an alpha numeric code,But as i have mentioned above i need to compare it with database values.
$chkEmp_Id=mysql_fetch_array(mysql_query("SELECT Emp_Id FROM talent_users WHERE Emp_Id='{$Emp_Id}' "));
after comparing with database values if the value is present then it should generate a different "Emp_Id",every time generated employee id should be compared with database values...hope u guys got it na?please help me to fix this...
$pool = array_merge (range ('a', 'z'), range(0, 9));
do
{
$hash = "";
for ($i = 0; $i < $lengthOfHash; ++$i)
{
$hash .= $pool[array_rand ($pool)];
}
while ( mysql_result (mysql_query ('SELECT COUNT(1) FROM talent_users WHERE Emp_Id = ' . $hash), 0) > 0);
But this is a big bottleneck when the table size grows. Since the hash is alpha-numeric, why can't the hash just begin with the userId?
//hash = <a number> + <a letter> + <alpha-numeric chars>
$hash = $userId . generateHash();
Just make sure that the generateHash() function doesn't start with a number, as stated in the comment.
It would then be something like:
$hash = $userId;
$letters = range ('a', 'z');
$pool = array_merge ($letters, range (0, 9));
for ($i = 0; $i < $lengthOfHash; ++$i)
{
$chooseFrom = $pool;
if ( ! $i )
$chooseFrom = $letters;
$hash .= $chooseFrom[array_rand($chooseFrom)];
}

Displaying the 0 in front of a number

I'm generating auto incremental code through a PHP script. The sequence goes like this, L001, L002....L039, L040. Below is the PHP code I have written. The comments show the output of each statement.
<?php
require_once("db_handler.php");
$conn = iniCon();
$db = selectDB($conn);
$query = "SELECT LID FROM locations ORDER BY LID DESC LIMIT 1";
$result = mysql_query($query, $conn);
$row = mysql_fetch_array($result);
$last_id = $row['LID']; //L040
$id_letter = substr($last_id, 0, 1); //L
$id_num = substr($last_id, 1) + 1; //040 + 1
$new_id = $id_letter . $id_num;
mysql_close($conn);
?>
I'm displaying the $new_id in a HTML textbox. though everything works fine up to this point, the new generated code shows as L41, cutting off the leading zero.
How can I stop this from happening? I need to have that zero in the front.
Thank you.
Use either str_pad or sprintf function:
$id_num = str_pad($id_num, 3, "0", STR_PAD_LEFT);
or
$id_num = sprintf("%03d", $id_num);
$id_num = substr($last_id, 1) + 1; //40 + 1
$id_num = str_pad($id_num, 3, "0", STR_PAD_LEFT); //return 041
$new_id = $id_letter . $id_num;
take a look at sprintf[1]. hint: %03d
[1] http://br2.php.net/sprintf

Categories