Common scenarios: If I want to add a unique album and a user's favorite record. Currently, I have two methods: Check whether there is an aid and uid in advance, and then determine whether to add-code layer. Add a uniquekey to the aid and uid, and then use trycatch of php to process it... common scenario: If I want to add a unique album and a user's favorite record.
Currently, I have two methods:
-
Check whether the aid and uid already exist in advance, and then determine whether to add ---- code layer.
-
Add the unique key to the aid and uid, and then use try catch in php to process it-database level.
Which of the above two methods is better? Are there any good php best practices?
Reply content:
Common scenarios: If I want to add a unique album and a user's favorite record.
Currently, I have two methods:
-
Check whether the aid and uid already exist in advance, and then determine whether to add ---- code layer.
-
Add the unique key to the aid and uid, and then use try catch in php to process it-database level.
Which of the above two methods is better? Are there any good php best practices?
Either way. Either way UNIQUE (aid,uid.
In terms of efficiency, try is better. Note that the catch should identify the error code. If the exception is not caused by a unique key conflict, it should be handled separately.
Add a keyword FieldUnique IndexAh! Simply look at the returned value of the database. How can your program judge it? It cannot be faster than the database itself.
MySQL? Replace ......
1. Simple and Direct
1. MySQL can use REPLACE
2. Otherwise, first check whether there is, replace if there is, and insert if there is no.
Note: avoid repeated submission and generate two identical records (the front-end form uses the token and the transaction is used in the above 2 ).