Reputation: 55
What happens is a user comes on site, fills create a new product form with title, description, price et cetera fields...
I want to store a unique generated alphanumeric key in my 'id' column which is set to auto_increment by default, use that unique key as my product_id. Like every Youtube video has its own generated unique key rather than having id like '1', '2', '3'....
I'm generating that key using "uniqid();"
function.
Please do let me know if I'm doing it wrong or there is better approach to do this. I'm a complete rookie.
Upvotes: 1
Views: 467
Reputation: 12277
The following two things cannot be true simultaneously:
You cannot have a alphanumeric key which is auto_increment because by definition, alphanumeric means a string created with alphabets and numbers and you cannot auto increment alphabets, makes sense?
So my suggestion is that you leave the "id" key numeric as 1, 2, 3 etc and create one more column in your table, name it "unique_id" lets say. Of course you can name it whatever you like. It needs to be VARCHAR(255) type.
And then populate that column using following functions:
$bytes = 12;
$uniqueId = bin2hex(openssl_random_pseudo_bytes($bytes)); //this will create 24 char alphanumeric string, you can increase or decrease it by changing the $bytes
and put this $uniqueId
into your column and voila, you have your unique id of the entity.
UPDATE
In order to show the alphanumeric unique id in your url, you need to change your url structure from /localhost/product/product_id
to /localhost/product/product_unique_id
and I am assuming you have somewhere your product listed with some kind of hyperlink, clicking on which takes user to the product detail page, right?
Let's say you had a product which has id 1 and unique id lt4Zhr7 so simply where you list products, you give the unique id of the product like so:
<a href="/localhost/product/lt4Zhr7"> Product 1 </a>
This is a basic solution which is supposed to guide you in the right direction, your actual code might be different based upon the framework you are using or some other factor.
Upvotes: 1