M
M
Muvka2019-06-08 17:54:20
MySQL
Muvka, 2019-06-08 17:54:20

How to get around the problem of creating the same codes?

I am finalizing the store on OpenCart. When a client submits a form, a promotional code like AAA-0001 should be created in the database, etc. in order. Tell me, is it better to store the last code in the options, or is it better to query the table with codes and find out the number of the last code? And most importantly, how to make sure that the same codes cannot appear? Is there such a possibility? Or not?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Sviridov, 2019-06-08
@dimuska139

Form this code based on the primary key of the table. That is, the user submitted the form, you made an entry in the database, and received its ID. And you generate a promotional code based on this ID. The ID within the table is unique, so your procode will be unique. You can form this promotional code not in PHP, but in the database, hang the trigger on the insert event. But I still advise you to do it in the code, because this way you can cover it with tests.

I
Ivan Melnikov, 2019-11-01
@immelnikoff

promotional code type AAA-0001

If the first three characters are static and only the numeric part changes, then just make a new table:
CREATE TABLE promocode(
id MEDIUMINT UNSIGNED NOT NULL AUTO_INCREMENT,
user_id INT NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY (user_id) REFERENCES user (id)
);

Now, when in the id field, a unique integer will be automatically generated, which can be used as a promo code. ps. I think that it is better to implement this generation of unique promotional codes on the database side, since in this case you will definitely guarantee the uniqueness of the promotional code for each user.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question