Mysql-PHP Best Practice: when adding unique data, do you need to query and compare the data in advance, or use trycatch for processing? Which efficiency is high?

Source: Internet
Author: User
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:

  1. Check whether the aid and uid already exist in advance, and then determine whether to add ---- code layer.

  2. 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:

  1. Check whether the aid and uid already exist in advance, and then determine whether to add ---- code layer.

  2. 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 ).

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.