In this tutorial, i will show to you on how to create or generate an id number in MySql using PHP with prefix, when you say with prefix, you can assign any value or text in-front or before the real id number, like for example if we create a Purchase Order number ID, so we can create a prefix like, PO-1, PO-2....PO-n. So, it is useful when you are assigning id number in a table with different value but the-same id number, and also if you are bored of MySql auto-generated id number.
So, how we can do this?
assuming we have a PO table in our database and having a column poID which data type is varchar, now we can achieve this PO-1 id, with the help of AGGREGATE function MAX, of-course we need a simple query.
//holding the id number
$id = NULL;
/*the prepare statement, preparing the query and we can now using the MAX aggregate function and querying from the table PO*/
$stmt = $this->Connect()->prepare("SELECT MAX(poID) FROM PO");
//executing the query
$stmt->execute();
//binding the result here
$stmt->bind_result($id);
//fetching the value
if($stmt->fetch()){
/*if $id variable id null it means the table is empty so we can simply assign the value to 1*/
if($id == NULL){
$res = 1;
}
/*if the poID column is not empty so we can use the substr function of a php extracting the PO- characters and separate the real id number,
if PO-1 so we can separate PO- and 1, like shown on the code below*/
else{
$res = substr($id, 3, strlen($id)) + 1;
}
}
//then if this codes are inside the function then we simply return the value
return "PO-" . $res;
you can customize of create your own id number with prefix using this codes, but the crucial part is the length of prefix and you can adjust the indexes.
hope this will help. Happy Coding!!! ;)
How to create auto-generated id number in MySql using PHP with prefix
on
0 comments:
Post a Comment