I am using this php code to generate a code
<?php
$year = date('y'); //gets 2 digits of year, ex, year 2014 as 14
$month = date('m');//gets 2 digits of month, ex, month July as 07
$day = date('d');//gets 2 digits of date, ex, date 07
$random = substr( md5(rand()), 0, 4); //generate 4 digits random number using 0-9 and a-z
$code = $year . $month . $day . $random;
echo $code;
?>
Next I am trying to add a 5 digit number to this code starting from 00001 to 99999
means the code shall look like, YYMMDDXXXXNNNNN while I have achieved YYMMDDXXXX, I am still struggling with NNNNN part (00000-99999).
How can that be made and concatenated to this variable $code with each user generate entry.
I want to mention here, this is the code number of a form, when 1st user fills the form on any date the NNNNN given to him would be 00001, for 2nd user 00002, 3rd user 00003 and so on, irrespective of any date in a particular month.
Also, When the month is changed from current to next, I want that NNNNN again to be reset to 00001.
How can I achieve those two things.
Any idea guys?
here is the snippet http://codepad.org/cgPLEtr7
You can use:
$form = sprintf("%05s", 1);
$code = $year . $month . $day . $random . $form;
to get the value of $code
right.
Below are a few more hints about your 'other' queries.
You could try setting up another MySQL table to store your 5-digit form number, which will initially be '00000', as a varchar
.
Then, on data insert
to your original table, trigger MySQL to update this value by +1 after a cast
, as in: https://stackoverflow.com/a/6873429/3318560
Draw this value to your form via PHP, and keep it there as a hidden value that you will append to your $code
.
Finally, you could use a MySQL event to reset your value to 00000
each month.
Firstly, create a table to store the counters in:-
CREATE TABLE month_counter
(
id INT NOT NULL AUTO_INCREMENT,
aMonth CHAR(6),
aCounter INT ,
PRIMARY KEY (`id`),
UNIQUE KEY `aMonth` (`aMonth`)
);
Then when you want a new value use:-
INSERT INTO month_counter (id, aMonth, aCounter)
VALUES(NULL, '201407', 1)
ON DUPLICATE KEY UPDATE id=LAST_INSERT_ID(id), aCounter=aCounter+1
When you execute that query from php you can use LAST_INSERT_ID() to get the id of the last inserted row, which you can then select the value from:-
$sql = "SELECT aCounter FROM month_counter WHERE id = ".LAST_INSERT_ID();
Note that the value could change between the INSERT and the SELECT, hence you should wrap this up in a transaction