I have a question, how to create/generate unique code based on current date or input date? For instance, input date = 02-02-2022, the code supposed to look like 20220202-000001.
You can create a Date object using the inegratedDateTime API.
Here you can find a list of available formatting options
THIS solution only shows one way to solve the OP's specific problem:
"I have a question, how to create/generate unique code based on current date or input date? For instance, input date = 02-02-2022, the code supposed to look like 20220202-000001.".
THIS solution does not attempt to create a UID across any/and all problem domains.
You could use str_replace() on the date to get rid of the dashes. Then use str_pad() on the count to fill it with 0's and have it "right justify" the actual count.
<?php
function makeCode($date, $count) {
$dateCode = str_replace("-", "", $date);
$countCode = str_pad(strval($count), 8, "0", STR_PAD_LEFT);
return $dateCode . "-" . $countCode;
}
// test
echo makeCode("02-02-2022", 1); // 02022022-00000001
?>
The 2nd parameter to str_pad() controls the width of the counter, how many zeroes will fill minus the string length the count intself.
Related
Currently i am tried to increment value by one but is not working while taking large length of digit.
For example..
Right now st_id is store in database like G4KZ00000001 now what i want when it's called second time then value will be increment by 1 so it would be then G4KZ00000002, G4KZ00000003 etc..
Following is my code..
Value get from DB..
$lastStconId =$last_api_record['st_consignment_id'];
Then Use following condition
if(empty($lastStconId)) {
$consignment_no = 'G4KZ00000001';
}else
{
$dataid = $last_api_record['st_consignment_id'];
$con = str_replace("G4KZ", "", $dataid);
echo $consignment_no = $con+1; // dynamic
echo $consignment_no = 'G4KZ'.$consignment_no;
}
When i print $consignment_no it's always return increment value but i want it with full string G4KZ00000002.
The problem is that when you increment $consignment_no with '00000001' you are getting 2 as this is a numeric value. To make it back to the full length you need to pad it out with zeros to the length of the original number. I use str_pad() with left padding with 0...
$consignment_no = 'G4KZ'.str_pad($consignment_no, strlen($con), "0", STR_PAD_LEFT);
You don't need to remove and re-add the G4KZ prefix at all - you can increment strings just fine in PHP. This also avoids the issue you're having with the padding being removed, since it treats the entire string as the operand.
$str = 'G4KZ00000001';
echo ++$str;
G4KZ00000002
See https://3v4l.org/nE8X9 for a demo with a few more iterations.
I am generating random numbers using php random function, but I want the generated number should be unique and it should not be repeated again.
----------
php code
$number = rand(100,100000); //a six digit random number between 100 to 100000
echo $number;
----------
but I am using this function for multiple times in my code for users so at very rare case there should be a chance of generating same number again. how can i avoid that.
I would do this:
You said you have branches. The receipt id could look something like this:
$dateString = date('Ymd'); //Generate a datestring.
$branchNumber = 101; //Get the branch number somehow.
$receiptNumber = 1; //You will query the last receipt in your database
//and get the last $receiptNumber for that branch and add 1 to it.;
if($receiptNumber < 9999) {
$receiptNumber = $receiptNumber + 1;
}else{
$receiptNumber = 1;
}
Update the receipt database with the receipt number.
$dateString . '-' . $branchNumber . '-' . $receiptNumber;
This will read:
20180406-101-1
This will be unique(Provided you do less than 10,000 transactions a day.) and will show your employees easily readable information.
If you are storing users in DB you should create column [ID] as primary key with auto increment and that would be best solution.
In other case I'd recommend you to simply store all user id's in ascending order from N to M by reading last ID and adding 1 to it because I see no real gain from random order that only adds complexity to your code.
There are many ways, example:
$freq = [];
$number = rand(100,100000);
$times = 10;
while($times-- > 0)
{
while(in_array($number, $freq))$number = rand(100,100000);
$freq[] = $number;
echo $number . "<br>";
}
This will print 10 random unique numbers.
random_int
(PHP 7)
<?php
$number = random_int(100, 100000);
echo $number;
All you need to do is use timestamp in php as timestamp never cross each other hence it will always generate unique number.You can use time() function in php.
The time() function is used to format the timestamp into a human desired format. The timestamp is the number of seconds between the current time and 1st January, 1970 00:00:00 GMT. It is also known as the UNIX timestamp.
<?php
$t=time();
echo $t;
?>
Also you add a rand() function and insert it in front of the $t to make it more random as if few users work at same time then the timestamp might collide.
<?php
$number = rand(100,100000);
$t=time();
$random = $number.''.$t;
echo $random;
?>
The above will reduce the chance to timestamp collide hence making the probability of number uniqueness almost 100%.
And if you make your column unique in your database then the php wont insert the number hence this bottleneck will ensure you will always get a unique random number.
bill_id not null unique
If you are using it for something like user id, then you can use uniqid for that. This command gets a prefixed unique identifier based on the current time in microseconds.
Here's how to use it:
string uniqid ([ string $prefix = "" [, bool $more_entropy = FALSE]] )
Where prefix is used if you are generating ids for a lot if hosts at the same time, you can use this to differentiate between various hosts if id is generated at the same microsecond.
more_entropy increases the likeness of getting unique values.
Usage:
<?php
/* A uniqid, like: 4b3403665fea6 */
printf("uniqid(): %s\r\n", uniqid());
/* We can also prefix the uniqid, this the same as
* doing:
*
* $uniqid = $prefix . uniqid();
* $uniqid = uniqid($prefix);
*/
printf("uniqid('php_'): %s\r\n", uniqid('php_'));
/* We can also activate the more_entropy parameter, which is
* required on some systems, like Cygwin. This makes uniqid()
* produce a value like: 4b340550242239.64159797
*/
printf("uniqid('', true): %s\r\n", uniqid('', true));
?>
this code must work
some description about code:
generate unique id
extract numbers form unique id with regex
gathering numbers from regex with a loop
<?php
$unique = uniqid("",true);
preg_match_all("!\d+!", $unique ,$matches);
print_r($matches);
$numbers = "";
foreach($matches[0] as $key => $num){
$numbers .= $num;
}
echo $numbers;
I want to generate unique identificator in following 12 numeric format:
YYYYMMDDXXXX
Example:
201403052318
Where:
YYYYMMDD is a current date value and other XXXX is randomly generated value.
$today = date("Ymd");
$rand = sprintf("%04d", rand(0,9999));
$unique = $today . $rand;
Daily required unique volume is about 100. What methods using PHP should I use to prevent possible duplicates in rand values or make all id maximum unique? Maybe possible use current time functions to compact these numbers in last 4 characters?
EDITED:
Unique value connected to MySQL database as prime index of table. It is initial values not connected to any stored information in database.
You can't rely on rand() , There is a possibility you will generate a duplicate (Pretty rare for a rand(0,9999) to generate a duplicate, but that will at some point).
So instead of going for rand(), just create an incremental value (say.. starting from 1) and append to your generated date.
Next time when you regenerate a new id, grab that incremental value's (say if you had stored it somewhere.. must be 1 right ?) status, increment it and append it to your new date.
Not an ideal solution.. (Critics welcome)
You can make use of a uniqid coupled with sha-1 and time and do a substr() on them for first 4 chars.
<?php
$today = date("Ymd");
$rand = strtoupper(substr(uniqid(sha1(time())),0,4));
echo $unique = $today . $rand;
OUTPUT :
201403094B3F
I needed to do something similar, a solution that would keep time and also keep the id unique and i ended up with a solution to use PHP function time() like this
$reference_number = 'BFF-' . time(); you can change the BFF to something that makes more sense to your business logic.
My unique reference id looks like BFF-1393327176 and the number can be converted from Unix to real time which will give you, Tue, 25 Feb 2014 11:19:36
I hope this helps
If the unique values generated once, you just need to make conditional choice for the rand value and store the value in an array which is going to be the condition -using inarray-:
$amount = 100; // the amount of ids
$previousValues = array();
for ($i = 0; $i < $amount; $i++){
$rand = rand(0,9999);
while (in_array($rand, $previousValues)){
$rand = rand(0, 9999);
}
$previousValues[] = $rand;
$today = date("Ymd");
$unique = $today.$rand;
echo $unique."\n";
}
Checkout this demo.
A possible solution for creating unique "Unique Order Number" is following, I assume that you have orders table and field order_number, then the code is:
$orderNumber = DB::table('orders')->max('order_number') + random_int(10, 100);
If first order number is inserted as "100000000000" that method will give you this numbers:
100000000025
100000000056
100000000089
100000000123
100000000199
100000000232
100000000249
with that approach there is no possibility for non-unique number, but cons is that each number is greater the previous (not 100% random) but that approach is acceptable for most of the cases.
How can I force the date format to output:
12/12/2012, 1/10/2012, 1/5/2012
instead of
12/12/2012, 01/10/2012, 01/05/2012?
My code is the following:
$adatefrom = date_create($_POST['datefrom']);
$adateto = date_create($_POST['adateto']);
$adatefrom = date_format($adatefrom, 'd/m/Y');
$adateto = date_format($adateto, 'd/m/Y');
Please do note that I have to format the date AFTER posting it.
Have a look at the PHP built in date function here
You will find that your solution is as simple as this:
date('j/n/Y',strtotime($_POST['datefrom']));
The key things to note are the characters used in the first parameter.
j represents the day without leading zeros
n represents the month without leading zeros
There are many other options you have, just have a read through the documentation.
Please note that a simple search of 'PHP date' on Google would have found this solution for you
$adatefrom = date_create($_POST['datefrom']);
$adateto = date_create($_POST['adateto']);
$adatefrom = date_format($adatefrom, 'j/n/Y');
$adateto = date_format($adateto, 'j/n/Y');
you are welcome! ;)
I am storing sms received from twilio in a database so I can use them later. When I did this in the sandbox it worked. However when I upgraded to a regular phone number the number received is the same as was sent to, but +1 (or for xxxxxxxxxx where the x's are the original number, it looks more like 1xxxxxxxxxx+)
I therefore changed the mysql_query to the following: but it is still not working. What can be done to recognize that this is the original phone number?
<?php
$starttime = time();
$number = $_POST['number'];
$number1 = "1" . $number;
$number2 = $number . "1";
$number3 = "+1" . $number;
$number4 = $number . "+1";
$number5 = "+" . $number . "1";
$number6 = "1" . $number . "+";
$number7 = $number."1+";
$received = mysql_query("SELECT * FROM sms_received
WHERE (responder='$number' OR responder='$number1'
OR responder='$number2' OR responder='$number3'
OR responder='$number4' OR responder='$number5'
OR responder='$number6' OR responder='$number6')
AND (body='y' OR body='yes' OR body='Y' OR body='Yes' OR 'yea' OR 'Yea')
AND timestamp BETWEEN ".date('Y-m-d H:i:s', strtotime($starttime))." AND NOW()");
?>
But still, nothing is being received. Any ideas how else I can check whether an sms has been received from the user? I can see in the database that it's there... but the mysql isn't finding it. It worked before, when the number sent was identical to the number received from, but with the added +1 it screws it up. (the code before just had WHERE responder = '$number' and it worked, but the additional variables didn't help it).
Does this code have too many OR's? Is that even a problem?
UPDATE:
Thanks, here is the function I'm using to strip the number down to xxxxxxxxxx format, before saving it to the database:
function checkPhone($responder){
$items = Array('/\ /', '/\+/', '/\-/', '/\./', '/\,/', '/\(/', '/\)/', '/[a-zA-Z]/');
$clean = preg_replace($items, '', $responder);
if (substr($clean, 0, 1) == "1") {
return substr($clean, 1, 10);
}
else {
return substr($clean, 0, 10);
}
}
$number = checkPhone($responder);
Twilio returns numbers in a format called E.164, which is an internationally recognized standard for phone number formatting.
In general, it's best practice to standardize the number to E164 BEFORE you store it in the database. That way you don't have to worry about storing different data with two different copies of the same number - eg 925-555-1234 and (925) 5551234.
Google has a libphonenumber library that will convert numbers for you. It works with Javascript, C++, Java, and Python.
If you are using PHP, and only using US/Canadian numbers, you can write a function to normalize phone numbers, that does something like the following:
- Strip out all non number characters from the phone number
(parentheses, dashes, spaces) - you can use a function like preg_replace
- if the phone number begins with a +1, do nothing
- if the phone number begins with a 1, add a +
- else, add a +1 to the beginning of the number.
- finally, store it in the database.
I hope that helps - please let me know if you have more questions.
Kevin
Your last or is redundantly $number6, it should be $number7.
Aside from that, you can do a few different things, such as in:
responder in ('$number', '$number1', '$number2', '$number3', '$number4', '$number5', '$number6', '$number7')
Or something like this:
responder like '%$number%'
Use a regular expression.
preg_match_all("{[0-9]+}",$number,$m);
$norm_num="+".implode($m[0]);
if(strlen($norm_num)<6)
exit('Too short!');
mysql_query("SELECT * FROM sms_received
WHERE responder='%$norm_num%'
AND body IN ('y','yes','Y','Yes','yea','Yea')
AND timestamp BETWEEN ".date('Y-m-d H:i:s', strtotime($starttime))." AND NOW()");