There is a always needs of generating unique number for various type of situation in any kind of development from shopping cart to guest book in all possible type of applications. There are so many ways to generating unique auto number in PHP. You can always use php random functions along with the time function to get the unique number.
If you are not so want to perform so much functions and length process on getting unique number, you can always use simple method of getting unique value with the use MySQL.
We can get a unique auto generated number from MySQL by creating an auto incremented field. MySQL will generate a unique number by incrementing the last number of the table and will automatically add to the auto incremented field. This is the best way to generate a trouble ticket number for a help desk system. In a school if a new student joins then all details of the student we can feed to student table and while using the insert query, MySQL will add one auto generated unique number to this auto incremented field. We need not have to specify any thing in our query while adding the auto incremented field data. After successfully adding the record we can get this unique number by using mysql_insert_id(). Now let us try how to create a such auto incremented field.
We have to make auto increment field integer ( obvious ) and also unique. The property set to auto increment. Here is the sql to create a autonumber table with one auto increment field to assign one unique ID.
CREATE TABLE `autonumber` (
`id` int(13) unsigned NOT NULL auto_increment,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=1049 ;
This will create one table called auto number starting with next auto number 1049. So when ever you need to get the new auto number or unique auto number value you have to just use insert query like this in your code:
Insert into autonumber (â€˜idâ€™) values (â€˜â€™) or die (â€œMySQL Error:â€.mysql_error());
This query will insert next number 1050 in to autonumber table.
You can get this newly generated auto number by the following function.
$New_AutoNumber = mysql_insert_id();
You can even combine this number with number generated with the time and random function to get more unique value.
Let me drop comment if anyone of you encounter problem in getting it?