I want to make a database primary key. I am using PHP uniqid() Function.
uniqid(php,true);
Basically I want to add Student IDs in student table of database
e.g PHP-16-001
In which PHP is 3 character Course ID , 16 is year and 001 is student ID.
I can Add this via "."
$id = "php"."date('Y')".$i;
in which $i is a variable who is incrementing but when I fetch data from database I got
php16001
How can I got all characters?
String concatenation operator in php is '.', so to get your extra '-' characters add them to you string, Check the below code. You should insert your unique id in database as "php-16-001". Make sure your $i variable is a string.
$id = "php-" . date('y-') . $i;
Separate them by some character which you can then split by.
$id = sprintf("php-%s-%s", date('Y'), $i);
To "split" it back to individual chunks use explode
$idParts = explode("-", $string);
A better way to do it:
if($i < 9)
{
$i='00'.$i;
}
$unique_id = "PHP-".date('Y')."-".$i;
Related
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 need to split a string in two so I can do a SELECT query in my DB. For example, I have the number '0801'. I need to split that number into '08' and '01'. How do I manage to do that?
This is easy to do using the substr() function, which lets you pull out parts of a string. Given your comment that you always have a four-digit number and want it split into two two-digit numbers, you want this:
$input = "0801";
$left = substr($input, 0, 2);
$right = substr($input, 2);
echo "Left is $left and right is $right\n";
According to your comment
The first 2 numbers. It's allways a 4 digit number and I allways need
to split it in 2 two digit numbers
You can simply use
$value = '0801';
$split = str_split($value, 2);
var_dump($split[0]);
var_dump($split[1]);
Just keep in mind $value variable should always be of a string type, not int.
you can use str_split and list
$str = '0801';
list($first,$second) = str_split($str,2);
echo $first;
// 08
echo $second;
// 01
No one gave a MySQL answer yet...
If you're selecting that number..
SELECT
SUBSTR(colname, 0, 2) as firstpart,
SUBSTR(colname, 2, 2) as secondpart
FROM table
This question already has answers here:
How to generate a random, unique, alphanumeric string?
(31 answers)
Closed 7 years ago.
I need to create unique id on user's every click link.
Let I have a code
<a class="popup-text" href="examplelink&aff_sub=<?php echo $up_id; ?>" data-toggle="modal">Upto Rs.10000 Cashback LED TVs
+ Get additional upto Rs. 4 Cashback from afft</a>
when user click on that link $up_id should be automatically generated. $up_id should change every time when user click on that link.
$up_id comes from following code
<?php
$up_id=md5(uniqid(rand(), true));
?>
but I am getting same id every time.
Instead of PHP you can generate random number by using javascript, tryout following code:
<a class="popup-text" href="examplelink" onclick="location.href=this.href+'?&aff_sub='+Math.floor((Math.random()*1000)+1);return false;" data-toggle="modal">Upto Rs.10000 Cashback LED TVs
+ Get additional upto Rs. 4 Cashback from afft</a>
Best solution for this would be, get current timestamp and take md5() of thst
$up_id = md5(current time stamp);
You can easily achieve this with the following function:
function random_string($length)
{
$string = "";
$chars = "abcdefghijklmanopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$size = strlen($chars);
for ($i = 0; $i < $length; $i++) {
$string .= $chars[rand(0, $size - 1)];
}
return $string;
}
Here you first generate an empty string, then you define a string with all chars you want. After you also counted the numbers of chars you can start with filling your new string. You just use a for-loop to do this. Everytime the loopcontent is called, there is one random char (from your $char) added to your empty string.
You use this function (for example if you want to store your ID in a variable) by simply typing:
$password = rand_string(15) //the number specified in brackets is the amount of characters in your password
So with this function, you can just always generate a random string (in your case, a unique ID).
Let me know, if you're experiencing any issues.
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.
Basically, the idea is that people filter search results on the length. However, length is stored in a text field, as this can be different from item to item. An item could be 16,20 metres, and another could be 8.1m.
How would one even start? Get all the possible values from the database, change them to the format that is filtered on (parse everything to numeric only, comma separated?), get the associated ID, and then only show all the info related to those IDs, or is there a way I haven't found yet?
Kind regards.
edit: Standardizing format is a solution, but not one I can apply in this situation. I am not allowed to do this. It gets worse - the filtering can have both a minimum and a maximum value. Minimum: 4 and maximum: 8 should show everything between those lengths. 6.1m, 7,82 metres, 5.
Because I couldn't change the way the database was set up (standardize is, keep separate fields for the length itself, a float/double, and a field for the appendix), I've decided to go with this approach.
First get all the possible lengths, then:
foreach($lengths as $length) {
$cLengths[$length['item_id']] = preg_replace("/[^0-9,.]/", "", str_replace(',', '.', $length['field_value']));
}
Assuming the page would then be called with &minLength=2&maxLength=10 in the URL:
$minLength = $_GET['minLength'];
$maxLength = $_GET['maxLength'];
if(!is_null($minLength) && !is_null($maxLength)) {
$filteredItems = '';
foreach($cLengths as $itemId => $cL) {
if($cL >= $minLength && $cL <= $maxLength) {
$filteredItems .= $itemId . ',';
}
}
$filteredItems = substr($filteredItems, 0, -1);
$where .= 'item_id IN(' . $filteredItems . ') AND ';
}
I would recommend to standardize a format for length. It is hard to filter numeric values stored in different formats.
You can use the LIKE operator to search for any pattern in a string:
SELECT * FROM table WHERE length LIKE '%filtervalue%'
I would simply enforce standard during your query. Assuming your length column is named "length" and you query table is "table":
SELECT something, replace(length,',','.') + 0 as mylen FROM `table` HAVING mylen BETWEEN 16.2 AND 18
It would not be very fast, you can also use replace + 0 directly in where, it would remove the need for HAVING that is:
SELECT something FROM `table` replace(length,',','.') + 0 BETWEEN 16.2 AND 18
Good Luck!