How To Generate A Ticket Id With Correct Length By Padding Middle With 0
I'm trying to generate a ticket id value with this format: yymm###### to be used in my database table. This expresses a 2-digit year, 2-digit month, and a 6-digit numeric id that
Solution 1:
Try changing this:
<?phpecho date('ym'). $tkid ;?>
to this:
<?phpecho date('ym') . str_pad($tkid, 6, '0', STR_PAD_LEFT); ?>
See str_pad().
Solution 2:
If this was my project, I'd let mysql
do all the work (and I'd use a prepared statement for security reasons).
To eliminate any KEYWORD / tablename clashes, I recommend backticking your group
table.
My query will increment the highest TICKET_ID
value for the selected groupid
(and left-pad it with zeros if you are still using this code at the start of the next millenium!). If there are no rows for the selected groupid
, then a new [yymm000000]
value will be delivered in the resultset.
if($stmt=$conn->prepare(
"(SELECT LPAD(`TICKET_ID`+1,10,'0') FROM `group`
WHERE `groupid`=? ORDER BY `TICKET_ID` DESC LIMIT 1)
UNION
(SELECT CONCAT(DATE_FORMAT(CURDATE(),'%y%m'),'000000'))
LIMIT 1;"
)
){
$stmt->bind_param("s",$tid);
$stmt->execute();
$stmt->bind_result($new_tkid);
$stmt->fetch();
echo"<input type=\"text\" name=\"TICKET_ID\" value=\"$new_tkid\" readonly=\"readonly\">";
$stmt->free_result();
}else{
echo"Query Syntax Error"; // echo mysqli_error($conn);
}
Not only does this provide essential security to your query, it puts all data manipulation in one place rather than mixing manipulation with echoing.
Functions used:
Solution 3:
Format request using printf
<?php printf('%s%06d', date('ym'), $tkid); ?>
Seriously, printf is a workhorse
Post a Comment for "How To Generate A Ticket Id With Correct Length By Padding Middle With 0"