Jump to content

Creating a sequential numbered ticket id


chowie

Recommended Posts

Hello everyone.  I have a piece of code that I need to get changed.  Currently I have a ticket system that creates an unique and random number, e.g. 5Z3GBJUUQR.  I would like to change the code so that I get a sequential number that continues to increment with the current date added to the number, e.g. 2011-07-04-00001, 2011-07-04-00002, etc.  Here is the current code that I have to work with.  Any help on this would greatly be appreciated.  I'm fairly new at php scripting, and I am stuck.  Thank you for your help.

 

Chris Howard

 

Current Code:

/* Generate tracking ID and make sure it's not a duplicate one */

$useChars = 'AEUYBDGHJLMNPQRSTVWXZ123456789';

$trackingID = $useChars{mt_rand(0,29)};

for($i=1;$i<10;$i++)

{

$trackingID .= $useChars{mt_rand(0,29)};

}

 

 

It's not clear from your post, but do you want the incrementing number to reset each day or does it continue with the next number the following day?

 

For example, this:

2011-07-04-00001
2011-07-04-00002
2011-07-05-00001

 

Or this:

2011-07-04-00001
2011-07-04-00002
2011-07-05-00003

 

The second option is actually easier to do. Just have an auto-increment field in the table (I assume you are using a database) AND a date field. The "ticket" number would be the concatenation of those two values.

Here is a solution if you want the id component to restart each day. It still uses three fields: ticket, id and date, but the difference is that the id field is not an auto-increment field and the ticket field is the primary index for the table.

//Get the last ticket entered for today
$query = "SELECT `id`
          FROM `tableName`
          WHERE  DATE(`date`) = DATE(NOW())
          ORDER BY `id` DESC
          LIMIT 1";
$result = mysql_query($query) or die(mysql_error());

//Detemine the new ticket id component
if(mysql_num_rows($result)==0)
{
    $ticketID = 1;
}
else
{
    $row = mysql_fetch_assoc($result);
    $ticketID = $row['id'] + 1;
}
$ticketDate = date("Y-m-d");
$newTicket =  "{$ticketDate}-{$ticketID}";

//Create INSERT query
$query = "INSERT INTO `tableName`
              (`ticket`, `date`, `id`)
          VALUES ('$newTicket', '$ticketDate', $ticketID)";
$result = mysql_query($query) or die(mysql_error());

I really don't see why you could not just use the ID as primary key & autoincrement, then use the ID as the identefier. Does it really matter if you have values like 2011-07-5-145 and 2011-07-5-146 ? You can still sort and arrange tickets for that day by the end of the ticked identifier if you want or need.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.